Angular material chips is one type of directive which is build in angular material. Generally we are using chips for represent a small set of information like tags, contact, etc. For using angular material chips we need to install dependency of angular material
For install angular material dependency :-
ng add @angular/material
Now, we are add modules of angular material dependency in app.module.ts :
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import {MatChipsModule} from '@angular/material/chips'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, MatChipsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Here, we are add ts code for chips in app.component.ts :
import { COMMA, ENTER } from '@angular/cdk/keycodes'; import { AfterViewInit, Component } from '@angular/core'; import { MatChipInputEvent } from '@angular/material/chips'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements AfterViewInit { visible = true; selectable = true; removable = true; addOnBlur = true; readonly separatorKeysCodes: number[] = [ENTER, COMMA]; ChipsValue: any[] = [ { name: 'test' }, { name: 'test 1' }, { name: 'test 2' }, { name: 'test 3' }, ]; ngAfterViewInit() { var value = document.getElementsByClassName("mat-form-field-underline")[0]; if (value) { value.classList.add("d-none") } } add(event: MatChipInputEvent): void { const input = event.input; const value = event.value; if ((value || '').trim()) { this.ChipsValue.push({ name: value.trim() }); } if (input) { input.value = ''; } } remove(fruit: any): void { const index = this.ChipsValue.indexOf(fruit); if (index >= 0) { this.ChipsValue.splice(index, 1); } } }
Here, we are add html code for chips in app.component.html :
<main class="wrapper"> <h2>Angular Material Chips</h2> <mat-form-field class="example-chip-list" style="width: 500px;"> <mat-chip-list #chipList> <div class="ms-2"> <h5 class="mb-0 ms-1">Enter chips name here..</h5> <input [matChipInputFor]="chipList" [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)" style="width: 200px;"> </div> <div class="mt-2"> <mat-chip *ngFor="let value of ChipsValue" [selectable]="selectable" [removable]="removable" (removed)="remove(value)"> {{value.name}} <p matChipRemove *ngIf="removable" class="mt-3">X</p> </mat-chip> </div> </mat-chip-list> </mat-form-field> </main>
Now, we are run our project
npm start
Output :