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

前端 未结 4 1675
野性不改
野性不改 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:08

    I combined the answer from @ama and this other answer to get the functionality I think you're describing. The key was to combine the optionActivated global variable with manually closing the autocomplete panel:

    1. Add optionActivated to your mat-autocomplete
    
    
    
  • Add the optionActivated function and global var
  • autocompleteTagsOptionActivated = false;
    
      optionActivated(event: MatAutocompleteActivatedEvent) {
        if (event.option) {
          this.autocompleteTagsOptionActivated = true;
        }
      }
    
    1. Add a accessor for the MatAutocompleteTrigger of your input
    @ViewChild('autoInput', { read: MatAutocompleteTrigger }) matAutocompleteTrigger: MatAutocompleteTrigger;
    
    
    1. Alter your inputTokenEnd to only process the input if there tags weren't activated and conditionally close the autocomplete
      inputTokenEnd(event: MatChipInputEvent): void {
        const input = event.input;
        const value = event.value;
    
        if ((value || '').trim() && !this.autocompleteTagsOptionActivated) {   
          this.value.push(value.trim());
        }
    
        // Reset the input value
        if (input) {
          input.value = '';
        }
        this.controlsForm.autocomplete.setValue(null);
    
        // If no autocomplete options were activated, then issue the command to close the panel.  The enter key that
        // triggers the input will inadventantly open the panel
        if (!this.autocompleteTagsOptionActivated) {
          this.matAutocompleteTrigger.closePanel()
        } 
      }
    
    1. Alter your optionSelected to reset the activation var
    
      optionSelected(event: MatAutocompleteSelectedEvent): void {
        this.autocompleteTagsOptionActivated = false;
    
        ...
      }
    

提交回复
热议问题