import { COMMA , ENTER } from '@angular/cdk/keycodes' ; import { Component , ElementRef , ViewChild } from '@angular/core' ; import { FormControl } from '@angular/forms' ; import { MatAutocompleteSelectedEvent , MatChipInputEvent , MatAutocomplete } from '@angular/material' ; import { Observable } from 'rxjs' ; import { map , startWith } from 'rxjs/operators' ; title @ Component ( { selector : 'chips-autocomplete-example' , templateUrl : 'chips-autocomplete-example.html' , styleUrls : [ 'chips-autocomplete-example.css' ] , } ) export class ChipsAutocompleteExample { visible = true ; selectable = true ; removable = true ; addOnBlur = true ; separatorKeysCodes : number [ ] = [ ENTER , COMMA ] ; fruitCtrl = new FormControl ( ) ; filteredFruits : Observable < string [ ] > ; fruits : string [ ] = [ 'Lemon' ] ; allFruits : string [ ] = [ 'Apple' , 'Lemon' , 'Lime' , 'Orange' , 'Strawberry' ] ; @ ViewChild ( 'fruitInput' ) fruitInput : ElementRef < HTMLInputElement > ; @ ViewChild ( 'auto' ) matAutocomplete : MatAutocomplete ; constructor ( ) { this . filteredFruits = this . fruitCtrl . valueChanges . pipe ( startWith ( null ) , map ( ( fruit ) => fruit ? this . _filter ( fruit ) : this . allFruits . slice ( ) ) ) ; } add ( event ) { if ( ! this . matAutocomplete . isOpen ) { const input = event . input ; const value = event . value ; if ( ( value || '' ) . trim ( ) ) { this . fruits . push ( value . trim ( ) ) ; } if ( input ) { input . value = '' ; } this . fruitCtrl . setValue ( null ) ; } } remove ( fruit ) { const index = this . fruits . indexOf ( fruit ) ; if ( index >= 0 ) { this . fruits . splice ( index , 1 ) ; } } selected ( event ) { this . fruits . push ( event . option . viewValue ) ; this . fruitInput . nativeElement . value = '' ; this . fruitCtrl . setValue ( null ) ; } private _filter ( value ) { const filterValue = value . toLowerCase ( ) ; return this . allFruits . filter ( fruit => fruit . toLowerCase ( ) . indexOf ( filterValue ) === 0 ) ; } }