Autocomplete with chip style in Angular using Angular Material

In this article, we’ll learn how to create autocomplete with chip style with input bi which you can add your own value also. For that, we have taken the example of the countries selection. How many countries you visited for that we have to implement autocomplete and also you can write your own if you not found. To start implementing that first, we need to install the angular material module in our application run below command to install the module.


npm i @angular/material
npm i @angular/flex-layout

After installing module lets add a module in our app.module.ts file. We need to import some modules to use our application called Button, Card, Input, Autocomplete, Chips display in the below code.


......
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {MatInputModule} from '@angular/material/input';
import {MatChipsModule} from '@angular/material/chips';
.....................
@NgModule({
imports:[ 
..., 
MatAutocompleteModule,
MatButtonModule,
MatCardModule,
MatInputModule,
MatChipsModule
...,   
],
....
})



After adding a module in the app.module file we can use it in our component to darw the autocomplete. Let’s create app.component.ts file to assign some defult values and some autocomplete values and add, delete to selected option.


/*
https://www.eduforbetterment.com/
*/
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  visible = true;
  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  countriesCtrl = new FormControl();
  filteredCountries: Observable;
  countries: string[] = ['India'];
  allCountries: string[] = ['India','USA', 'UK', 'Australia', 'Belgium', 'New Zealand','Canada','Philippines','Russia'];

  @ViewChild('countryInput') countryInput: ElementRef;
  @ViewChild('auto') matAutocomplete: MatAutocomplete;

  constructor() {
    this.filteredCountries = this.countriesCtrl.valueChanges.pipe(
        startWith(null),
        map((country: string | null) => country ? this._filter(country) : this.allCountries.slice()));
  }

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;

    // Add our country
    if ((value || '').trim()) {
      this.countries.push(value.trim());
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }

    this.countriesCtrl.setValue(null);
  }

  remove(country: string): void {
    const index = this.countries.indexOf(country);

    if (index >= 0) {
      this.countries.splice(index, 1);
    }
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    this.countries.push(event.option.viewValue);
    this.countryInput.nativeElement.value = '';
    this.countriesCtrl.setValue(null);
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.allCountries.filter(country => country.toLowerCase().indexOf(filterValue) === 0);
  }
}

Display below is the code for the app.component.ts ,app.component.html,app.component.css


/*
https://www.eduforbetterment.com/
*/
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  visible = true;
  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  countriesCtrl = new FormControl();
  filteredCountries: Observable;
  countries: string[] = ['India'];
  allCountries: string[] = ['India','USA', 'UK', 'Australia', 'Belgium', 'New Zealand','Canada','Philippines','Russia'];

  @ViewChild('countryInput') countryInput: ElementRef;
  @ViewChild('auto') matAutocomplete: MatAutocomplete;

  constructor() {
    this.filteredCountries = this.countriesCtrl.valueChanges.pipe(
        startWith(null),
        map((country: string | null) => country ? this._filter(country) : this.allCountries.slice()));
  }

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;

    // Add our country
    if ((value || '').trim()) {
      this.countries.push(value.trim());
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }

    this.countriesCtrl.setValue(null);
  }

  remove(country: string): void {
    const index = this.countries.indexOf(country);

    if (index >= 0) {
      this.countries.splice(index, 1);
    }
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    this.countries.push(event.option.viewValue);
    this.countryInput.nativeElement.value = '';
    this.countriesCtrl.setValue(null);
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.allCountries.filter(country => country.toLowerCase().indexOf(filterValue) === 0);
  }
}


<div class="example-container mat-elevation-z8">

 <mat-form-field class="example-chip-list">
  <mat-chip-list #chipList aria-label="Country selection">
    <mat-chip
      *ngFor="let country of countries"
      [selectable]="selectable"
      [removable]="removable"
      (removed)="remove(country)">
      {{country}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input
      placeholder="Select Countries ..."
      #countryInput
      [formControl]="countriesCtrl"
      [matAutocomplete]="auto"
      [matChipInputFor]="chipList"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      (matChipInputTokenEnd)="add($event)">
  </mat-chip-list>
  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
    <mat-option *ngFor="let country of filteredCountries | async" [value]="country">
      {{country}}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

</div>




Output

Below is the full embeded code for the autocomplete using angular material you can easily used in your application.
Example

Spread the love
  •  
  •  
  •  
  •  
  •  
  • 2
  •  
  •