Angular eslint @angular-eslint/template/no-call-expression

679 Views Asked by At

I have a material table that contains a checkbox for each row which I want to bind the checked attribute in the following way:

<mat-checkbox [checked]="selection.isSelected(row)" ...></mat-checkbox>

But when I run ng lint on my library I get the the @angular-eslint/template/no-call-expression lint error on the checked binding which is kind of obvious. However I have no idea how to avoid using call expression on this. The selection (which here is a CDK SelectionModel<any>) type is the container of the selection status of the row, so I have to get the row status from here. It is not possible to set a flag on the row.

Anyone have any solution on how to avoid calling expression in these kind of bindings?

1

There are 1 best solutions below

0
On

I'm not 100% sure on the background of your question but most CDK components allow you to query their status. The solution would then be to

  1. subscribe to changes on the selected items
  2. have a private array of isSelected values indexed by some means of identifying a row
  3. read the value from that array i.e. isRowSelected[rowIndex].

About 1: The SelectionModel has two ways to interact with the selected values: a) the "changed" event that emits whenever the value changes and b) the "selected" output that updates when the value does. So you can, for example, have a dictionary on your component where the keys are the selectable values and the values are the associated "isSelected" values. Then add a listener to SelectionModel.changed that does something like:

selectionModel.changed.subscribe((change: SelectionChange) => {
   console.log(change); 
})

The type SelectionChanged has 3 members: source, added and removed. So you can either use source in the callback to access which values are currently selected or not or you can iterrate over added and set the corresponding values in your array to true and over removed and set the corresponding values to false. This version would be succeptible to drift but would be faster if you have very many rows. Hope this helps.