Search code examples
angularangular-pipeangular10

Using Angular pipes to set css class


I have an angular material autocomplete that allows users to select multiple options. The options that user selected must appear in red color to indicate that they were already selected. If the user selects them again, the option gets unselected. I know that using a class method in template is not good for the performance, so I created a pipe to achieve that. However, the pipe only receives the values in the dropdown when the component loads.

How can I resolve this?

<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 is an array that stores the selected options

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

Where am I going wrong?


Solution

  • try

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