11import { COMMA , ENTER } from '@angular/cdk/keycodes' ;
22import { Component , ElementRef , ViewChild } from '@angular/core' ;
33import { FormControl } from '@angular/forms' ;
4- import { MatAutocompleteSelectedEvent , MatChipInputEvent } from '@angular/material' ;
4+ import { MatAutocompleteSelectedEvent , MatChipInputEvent , MatAutocomplete } from '@angular/material' ;
55import { Observable } from 'rxjs' ;
66import { map , startWith } from 'rxjs/operators' ;
77
@@ -17,14 +17,15 @@ export class ChipsAutocompleteExample {
1717 visible = true ;
1818 selectable = true ;
1919 removable = true ;
20- addOnBlur = false ;
20+ addOnBlur = true ;
2121 separatorKeysCodes : number [ ] = [ ENTER , COMMA ] ;
2222 fruitCtrl = new FormControl ( ) ;
2323 filteredFruits : Observable < string [ ] > ;
2424 fruits : string [ ] = [ 'Lemon' ] ;
2525 allFruits : string [ ] = [ 'Apple' , 'Lemon' , 'Lime' , 'Orange' , 'Strawberry' ] ;
2626
2727 @ViewChild ( 'fruitInput' ) fruitInput : ElementRef < HTMLInputElement > ;
28+ @ViewChild ( 'auto' ) matAutocomplete : MatAutocomplete ;
2829
2930 constructor ( ) {
3031 this . filteredFruits = this . fruitCtrl . valueChanges . pipe (
@@ -33,20 +34,24 @@ export class ChipsAutocompleteExample {
3334 }
3435
3536 add ( event : MatChipInputEvent ) : void {
36- const input = event . input ;
37- const value = event . value ;
37+ // Add fruit only when MatAutocomplete is not open
38+ // To make sure this does not conflict with OptionSelected Event
39+ if ( ! this . matAutocomplete . isOpen ) {
40+ const input = event . input ;
41+ const value = event . value ;
3842
39- // Add our fruit
40- if ( ( value || '' ) . trim ( ) ) {
41- this . fruits . push ( value . trim ( ) ) ;
42- }
43+ // Add our fruit
44+ if ( ( value || '' ) . trim ( ) ) {
45+ this . fruits . push ( value . trim ( ) ) ;
46+ }
4347
44- // Reset the input value
45- if ( input ) {
46- input . value = '' ;
47- }
48+ // Reset the input value
49+ if ( input ) {
50+ input . value = '' ;
51+ }
4852
49- this . fruitCtrl . setValue ( null ) ;
53+ this . fruitCtrl . setValue ( null ) ;
54+ }
5055 }
5156
5257 remove ( fruit : string ) : void {
0 commit comments