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

前端 未结 4 1674
野性不改
野性不改 2021-02-09 19:41

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

4条回答
  •  生来不讨喜
    2021-02-09 20:02

    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);
    }

提交回复
热议问题