角材料:如何将数据映射到角材料表中的标题?

时间:2019-11-01 07:05:44

标签: angular angular-material dynamic-data angular-material-table

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

这里是代码:stackblitz

样品

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

sample.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
        },
      ]
    }
  ]
}
];

1 个答案:

答案 0 :(得分: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;
        })
  }
}

我不确定您要准确实现什么目标,因此我发布了一些函数,这些函数可以总体上按元素,宗地或按项为您提供独特的类别。

希望这会帮助您继续进行。