Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material, Mat Chips Autocomplete Bug, matChipInputTokenEnd executed before optionSelected

When typing some text into the input and selecting an option from the autocomplete by hiting enter, it saves as chips both of the strings. Image here

However, this doesn't happen when selecting an option from the autocomplete with the mouse.

In the example provided on Angular Material Autocomplete Chips, in the case described, the optionSelected fires first, while in the same code on my local machine it is executed after matChipInputTokenEnd, thus, leading to the bug.

Has anyone encountered this problem?

like image 681
L. Aames Avatar asked Oct 02 '18 12:10

L. Aames


2 Answers

Regarding the selection event, when you press ENTER, both the matChipInputTokenEnd, from your input, and the optionSelected, from mat-autocomplete, will fire. Normally, this happens with the optionSelected first, so that when the input event fires, the chip will already be added and the input will have no value to add. This is the reason why you don't get this issue by clicking with your mouse, since only the optionSelected event will be fired.

Now I said normally because I've also been getting this problem on a module imported component. If this is your case, this is probably a bug.

However, I did find a quick solution. What I did was check if the mat-autocomplete dialog was open and prevent the mat-chip-input from adding a new element. Checking for a selected item on the options list is also a possibility but it's less performant and not the behavior I was looking for.

Hope this helps:

@ViewChild('chipAutocomplete') chipAutocomplete: MatAutocomplete;

addElement(event: MatChipInputEvent) {
  if ((event.value || '').trim() && !this.chipAutocomplete.isOpen) {
    this.value.push({
      name: event.value.trim()
    });
  }

  if (event.input) {
    event.input.value = '';
  }

  this.chipInputControl.setValue(null);
}
like image 56
André Dias Avatar answered Nov 12 '22 12:11

André Dias


it worked for me when I changed the order when importing modules. Import MatAutocompleteModule before MatChipsModule.

like image 3
Vo Minh Khanh Avatar answered Nov 12 '22 12:11

Vo Minh Khanh