1
1
import { COMMA , ENTER } from '@angular/cdk/keycodes' ;
2
2
import { Component , ElementRef , ViewChild } from '@angular/core' ;
3
3
import { FormControl } from '@angular/forms' ;
4
- import { MatAutocompleteSelectedEvent , MatChipInputEvent } from '@angular/material' ;
4
+ import { MatAutocompleteSelectedEvent , MatChipInputEvent , MatAutocomplete } from '@angular/material' ;
5
5
import { Observable } from 'rxjs' ;
6
6
import { map , startWith } from 'rxjs/operators' ;
7
7
@@ -17,14 +17,15 @@ export class ChipsAutocompleteExample {
17
17
visible = true ;
18
18
selectable = true ;
19
19
removable = true ;
20
- addOnBlur = false ;
20
+ addOnBlur = true ;
21
21
separatorKeysCodes : number [ ] = [ ENTER , COMMA ] ;
22
22
fruitCtrl = new FormControl ( ) ;
23
23
filteredFruits : Observable < string [ ] > ;
24
24
fruits : string [ ] = [ 'Lemon' ] ;
25
25
allFruits : string [ ] = [ 'Apple' , 'Lemon' , 'Lime' , 'Orange' , 'Strawberry' ] ;
26
26
27
27
@ViewChild ( 'fruitInput' ) fruitInput : ElementRef < HTMLInputElement > ;
28
+ @ViewChild ( 'auto' ) matAutocomplete : MatAutocomplete ;
28
29
29
30
constructor ( ) {
30
31
this . filteredFruits = this . fruitCtrl . valueChanges . pipe (
@@ -33,20 +34,24 @@ export class ChipsAutocompleteExample {
33
34
}
34
35
35
36
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 ;
38
42
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
+ }
43
47
44
- // Reset the input value
45
- if ( input ) {
46
- input . value = '' ;
47
- }
48
+ // Reset the input value
49
+ if ( input ) {
50
+ input . value = '' ;
51
+ }
48
52
49
- this . fruitCtrl . setValue ( null ) ;
53
+ this . fruitCtrl . setValue ( null ) ;
54
+ }
50
55
}
51
56
52
57
remove ( fruit : string ) : void {
0 commit comments