Search code examples
angularfilterangular-materialfilteringmat-table

angular 2+, mat table - filtering not working for model in model


I have mat-table with dataSource that models looks like this:

.ts

interface DataModel {
  id: number;
  projectName: string;
  material: material;
}

interface material {
  materialID: number;
  materialName: string;
}

.html

<mat-form-field>
  <mat-label>Filter</mat-label>
  <input matInput (keyup)="applyFilter($event)" placeholder="" #input>
</mat-form-field>

<div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource" matSort>

   
    <ng-container matColumnDef="projectName">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> projectName</th>
      <td mat-cell *matCellDef="let row"> {{row.projectName}} </td>
    </ng-container>
    <ng-container matColumnDef="material">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> material </th>
      <td mat-cell *matCellDef="let row"> {{row.material ? row.material.materialName  : ''  }} </td>
    </ng-container>
 <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

 
    <tr class="mat-row" *matNoDataRow>
      <td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
    </tr>
  </table>
  1. Filtering from the mat table does not work for material cell.
  2. The last line of tr, which should show the message if there is no match, doesn't work.

Thanks for help.

Edit.: Angular ver.: 8.0 Example: https://stackblitz.com/edit/angular-cxmmdz?file=src/app/table-filtering-example.ts - filtering not working for {{row.color.name}}


Solution

  • Ok I found simply solution.

    export interface UserData {
      id: number;
      name: string;
      color: string;
    }
    export interface ColorName {
      id: number;
      name: string;
    }
    const ELEMENT_DATA_COLOR: ColorName[] = [
      {id: 1, name: 'red'},
      {id: 2, name: 'orange'}
    ];
    const ELEMENT_DATA: UserData[] = [
      {id: 1, name: 'one',color:ELEMENT_DATA_COLOR[0].name },
      {id: 2, name: 'two',color: ELEMENT_DATA_COLOR[1].name}
    ];
    

    But I have one question. I get data from .net core API. and it looks like:

       const ELEMENT_DATA: UserData[] = [
          {id: 1, name: 'one',color:ELEMENT_DATA_COLOR[0] },
          {id: 2, name: 'two',color: ELEMENT_DATA_COLOR[1]}
        ];
    

    so if I want filtering works I need to save data to another model where color is string not object Color because filtering not working for {{row.color.name}} (using for ex. AutoMapper) ?