corry
corry

Reputation: 1529

Angular Material Chips activated chip ngclass

There is a definition

<mat-chip-list>
  <mat-chip 
    *ngFor="let chip of chips"
    [ngClass]="isActive(chip)"
    (click)="setActiveChip(chip)">
    {{ chip.name }}
  </mat-chip>
</mat-chip-list>

which has isActive function for setting chip active based on variable cardId:

isActive(chip) {
  const cardId = 2;
 
  if(cardId) {
     const activeChip = chip.id === cardId;
     return activeChip ? 'mat-chip-active' : '';
   }
 }

How to set ngClass to the other chip using another(setActiveChip) function?

Stackblitz

Upvotes: 0

Views: 1525

Answers (1)

huan feng
huan feng

Reputation: 8623

Please see:

https://stackblitz.com/edit/set-active-chip-nvg8no

import { Component } from "@angular/core";
import { MatChipInputEvent } from "@angular/material";

@Component({
  selector: "chips-overview-example",
  templateUrl: "chips-overview-example.html",
  styleUrls: ["chips-overview-example.css"]
})
export class ChipsOverviewExample {

  chips = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" }
  ];
  // Set default to the 2nd chip
  activeChip = this.chips[1];

  setActiveChip(chip) {
    this.activeChip = chip;
  }
}

HTML:

<mat-chip-list>
  <mat-chip 
    *ngFor="let chip of chips"
    [ngClass]="{'mat-chip-active': activeChip === chip}"
    (click)="setActiveChip(chip)">
    {{ chip.name }}
  </mat-chip>
</mat-chip-list>

Upvotes: 3

Related Questions