Angular Material 2 DataTable Sorting with nested objects

前端 未结 11 905
孤街浪徒
孤街浪徒 2020-11-29 17:25

I have a normal Angular Material 2 DataTable with sort headers. All sort are headers work fine. Except for the one with an object as value. These doesn\'t sort at all.

11条回答
  •  旧巷少年郎
    2020-11-29 18:05

    You can write a function in component to get deeply property from object. Then use it in dataSource.sortingDataAccessor like below

    getProperty = (obj, path) => (
      path.split('.').reduce((o, p) => o && o[p], obj)
    )
    
    ngOnInit() {
      this.dataSource = new MatTableDataSource(yourData);
      this.dataSource.sortingDataAccessor = (obj, property) => this.getProperty(obj, property);
      this.dataSource.sort = sort;
    }
    
    columnDefs = [
      {name: 'project.name', title: 'Project Name'},
      {name: 'position', title: 'Position'},
      {name: 'name', title: 'Name'},
      {name: 'test', title: 'Test'},
      {name: 'symbol', title: 'Symbol'}
    ];
    

    And in html

    
          {{ col.title }}
          
            {{ getProperty(row, col.name) }}
          
      
    

提交回复
热议问题