0

I have created a mat chip like below.

HTML

<mat-chip-list multiple>
    <mat-chip class="chip_margin cursor mt-3" *ngFor="let chip of chips" selectable="true"
     [selected]="isSelected(chip)" (click)="onClick($event, chip);">
   <span class="unselectableText">{{chip.ViewValue}}</span>
    </mat-chip>
</mat-chip-list>

TS:

 isSelected(chip:any) {        
    return this.chipCollection.get(chip.value);
 }

Problem:

"isSelected" function is calling n number of times how to solve this. Thanks in Advance.

jake clark
  • 71
  • 6

2 Answers2

0

Your problem is that isSelected is called in the binding [selected]="isSelected(chip)" which means that every time that angular runs the change detection it gets called.

To avoid this you have 2 solutions, the first one is to compute isSelected in another place and store a variable.

The second solution could be to switch to the OnPush change detection but then you must handle the fact that change detection will only run when inputs change.

Fabio Carpinato
  • 1,121
  • 6
  • 13
0

This has been cleared multiple times already.

One of the fix is to execute the function in the controller (*.ts) during the initialization of the this.chips member variable.

Controller (*.ts)

// assuming `this.chips` is initialized in a subscription

this.someService.getChips().pipe(
  map((chips: any) =>                    // <-- RxJS `map` operator
    chips.map((chip: any) => ({          // <-- JS `Array#map` function
      ...chip,
      isSelected: this.isSelected(chip)  // <-- introduce additional property
    })
  )
).subscribe({
  next: (chips: any) => this.chips = chips,
  error: (error: any) => console.log(error)
});

Template (*.html)

<mat-chip-list multiple>
  <mat-chip 
    class="chip_margin cursor mt-3" 
    *ngFor="let chip of chips" 
    selectable="true"
    [selected]="chip.isSelected" 
    (click)="onClick($event, chip);"
  >
    <span class="unselectableText">{{chip.ViewValue}}</span>
  </mat-chip>
</mat-chip-list>
ruth
  • 29,535
  • 4
  • 30
  • 57