Francesca Palù
Francesca Palù

Reputation: 41

Why cdkRowDefWhen in cdk table is not working

I'm trying to use a feature of angular material cdk tables, but I don't see it working, and maybe someone can tell me what I'm doing wrong. The feature is add a condition to show a row or not, and the cdk table provides it with the cdkRowDefWhen. So, to implement this, in my template I defined the cdkRowDef in this way:

<tr
  cdk-row
  *cdkRowDef="let row; columns: displayedColumns; when: showRow"
  class="bm-rt-table-row"
></tr>

where showRow is defined in the component as

showRow(_index: number, row: Recording) {
  return !row.id //my condition
}

and it never even executes the showRow. Am I doing something wrong? I don't see open issues about this, so I suppose that shouldn't be a problem of the cdk. Thanks

Upvotes: 1

Views: 877

Answers (1)

Mr. Stash
Mr. Stash

Reputation: 3140

You will need more than one cdk-row, the cdk-row template for which the 'when' function returns a true value will be displayed. So your code would look something like this.

displayedColumns: string[] = ['id', 'name', 'weight', 'symbol'];
displayedColumns1: string[] = ['id', 'name'];

showRowTemplate(_index: number, row: PeriodicElement) {
return row.id % 2 === 0
}

showRowTemplate1(_index: number, row: PeriodicElement) {
  return row.id % 2 !== 0 
}
<tr
  cdk-row
  *cdkRowDef="let row; columns: displayedColumns; when: showRowTemplate"
></tr>
<tr
  cdk-row
  *cdkRowDef="let row; columns: displayedColumns1; when: showRowTemplate1"
></tr>

In this example, the rows with odd ids will not have the weight and symbol columns but the even rows will

Upvotes: 1

Related Questions