1

如何将动态数据映射到角度材料表中的相应标题?我有按类别过滤数据的情况(在 parcelItems 下总是会有 2 个类别但未排序),如下所示。在这种情况下, Wears and Accessories是标题。Api 响应未在后端排序。我怎样才能做到这一点?

这是代码:stackblitz

样本

|---------------------|------------------------------|
|  Heading 1 (Wears)  |   Heading 2 (Accessories)    |
|---------------------|------------------------------|
|      jeans          |         earphones            |
|---------------------|------------------------------|
|      t-shirt        |         motherboard          |
|---------------------|------------------------------|

示例.json

const ELEMENT_DATA: Array<Data> = [
{
  fname: "Mark",
  lname: "jhony",
  parcels: [
    {
      parcelId: 123,
      parcelName: "parcel1",
      parcelItems: [
        { 
          name: "jeans",
          category: "wears",
          qty: 2
        },
        { 
          name: "earphones",
          category: "accessories",
          qty: 4
        },
      ]
    },
    {
      parcelId: 144,
      parcelName: "parcel2",
      parcelItems: [
        { 
          name: "motherboard",
          category: "accessories",
          qty: 5
        },
        { 
          name: "t-shirt",
          category: "wears",
          qty: 7
        },
      ]
    }
  ]
}
];
4

1 回答 1

0

检查以下代码:

/**
 * @title Basic use of `<mat-table>` (uses display flex)
 */
@Component({
  selector: 'table-basic-flex-example',
  styleUrls: ['table-basic-flex-example.css'],
  templateUrl: 'table-basic-flex-example.html',
})
export class TableBasicFlexExample implements OnInit {
  displayedColumns: string[] = ['fname', 'lname', 'parcels'];
  dataSource = ELEMENT_DATA;
  categories: any[] = [];
  ngOnInit() {
    this.dataSource.forEach(
      (element) => {
        this.categories = this.categories.concat(
          this.getCategoriesByElement(element)
        );
      }
    );
    this.categories = this.categories.
      filter( // Get unique items only
        (v, i, a) => a.indexOf(v) === i);
    console.log(this.categories);
  }
  getCategoriesByElement(element): any[] {
      var elementCategories = [];
      element.parcels.forEach(
        (parcel) => {
          elementCategories = elementCategories.concat(this.getCategoriesByParselItems(parcel.parcelItems));
        }
      );
      return elementCategories;
  }

  getCategoriesByParselItems(parcelItems: any[]) {
    return parcelItems
    .map( // Get category only
      (item) => {
        console.log(item.category);
        return item.category;
        })
  }
}

我不确定您想要准确地实现什么,所以我发布了一些功能,可以按元素或包裹或项目为您提供整体独特的类别。

希望这将帮助您继续。

于 2019-11-01T08:24:00.057 回答