我做了一个像下面这样的垫片。
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);
}问题:
"isSelected“函数调用n次如何解决这个问题。提前谢谢。
发布于 2021-07-29 10:42:15
您的问题是,isSelected在绑定selected=“isSelected(芯片)”中被调用,这意味着每当该角度运行变化检测时,它都会被调用。
为了避免这种情况,您有两个解决方案,第一个是在另一个地方计算isSelected并存储一个变量。
第二种解决方案可能是切换到OnPush更改检测,但是必须处理这样一个事实,即更改检测只能在输入更改时运行。
发布于 2021-07-29 10:46:42
修复方法之一是在初始化*.ts成员变量时在控制器( this.chips )中执行函数。
控制器(*.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)
});模板(*.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>https://stackoverflow.com/questions/68574429
复制相似问题