首页 > 解决方案 > 使用 Angular 管道设置 css 类

问题描述

我有一个角度材料自动完成功能,允许用户选择多个选项。用户选择的选项必须以红色显示,以表明它们已被选中。如果用户再次选择它们,则该选项将被取消选择。我知道在模板中使用类方法对性能不利,所以我创建了一个管道来实现这一点。但是,管道仅在组件加载时接收下拉列表中的值。

我该如何解决这个问题?

<mat-form-field>
  <input type="text" placeholder="Advisor Name/Port ID" aria-label="advisor-autocomplete" matInput
    [formControl]="advisorName" [matAutocomplete]="advisorAC"/>

  <mat-autocomplete #advisorAC="matAutocomplete"
    (optionSelected)="optionSelected($event)">
    <mat-option *ngFor="let advisor of filteredAdvisors | async" [value]="advisor.advisorPortId">
      <span
        [ngClass]="{'option--selected': advisor.advisorPortId | isSelected:selectedAdvisors}">{{ advisor.advisorFullName + ' (' + advisor.advisorPortId + ')' }}</span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

selectedAdvisors是一个存储所选选项的数组

@Pipe({
      name: 'isSelected',
    })
    export class IsSelectedPipe implements PipeTransform {
      transform(value: string, selectedValues: string[]): boolean {
        console.log(value);
        console.log(selectedValues);
    
        return selectedValues.includes(value);
      }
    }

我哪里错了?

标签: angularangular-pipeangular10

解决方案


尝试

@Pipe({
    name: 'isSelected',
    pure: false // this is the key
})

推荐阅读