Search code examples
javascriptangularangular7angular-material-7

Angular material chips removable


I want to remove the matChip on click of cancel icon
here is my code

<mat-chip-list>
    <mat-chip
        *ngFor="let user of data.users"
         [removable]="true"
         [selectable]="true"
         (removed)="remove(user.id)">
         {{user.name}}
         <mat-icon matChipRemove>cancel</mat-icon>
    </mat-chip>
</mat-chip-list>

Even though [removable]="true" is set it is not removing the clicked chip I have been following this docs example


Solution

  • Working example. Please, find the update files from your above link (which is available in your question) as below, while other files remains as same. If you want to check the working code, then try to replace the whole code in respective files of your link with below code to same files.

    NOTE: for better readability, I have removed input element with add functionality.

    chips-input-example.html

    <mat-form-field class="example-chip-list">
        <mat-chip-list #chipList aria-label="User selection">
            <mat-chip *ngFor="let user of data.users" [selectable]="selectable" [removable]="removable"
                (removed)="remove(user.id)">
                {{user.name}}
                <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
            </mat-chip>
        </mat-chip-list>
    </mat-form-field>
    

    chips-input-example.ts

    import {Component} from '@angular/core';
    
    interface User {
      name: string;
      id: number;
    }
    
    interface Data {
      users: User[];
    }
    
    @Component({
      selector: 'chips-input-example',
      templateUrl: 'chips-input-example.html',
      styleUrls: ['chips-input-example.css'],
    })
    export class ChipsInputExample {
      selectable = true;
      removable = true;
      data: Data = {
        users: [
        {name: 'User1', id: 0},
        {name: 'User2', id: 1},
        {name: 'User3', id: 2},
      ]};
    
      remove(getId: number): void {
        this.data.users = [...this.data.users.filter(({id}) => getId !== id)];
      }
    }
    

    chips-input-example.css

    .example-chip-list {
      width: 100%;
    }