3
votes

Here in this Stackblitz I have a mat-autocomplete with async data.

When (optionSelected) fires (when I click on an option) I want the field to be fully resetted like its freshly rendered/ initialised.

Currently this solution has two problems!

  1. after clearance I dont get any autosuggestions. I want to have the full autosuggestions back again.

==> I do have to blur and focus again or start typing.

  1. when I DON'T type and just blur and refocus I still have the mat-option.mat-selected class attached to the panel since the reset did only affect the input value. I highlighted this with background-color: red;.
1

1 Answers

4
votes

You need to make your reset function something like below

resetAutoInput(optVal, trigger: MatAutocompleteTrigger, auto: MatAutoComplete) {
    setTimeout(_ => {
      auto.options.forEach((item) => {
        item.deselect()
      });
      this.myControl.reset('');
      trigger.openPanel();
      }, 100);
  }

and in your HTML code will be

<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" #trigger="matAutocompleteTrigger" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="resetAutoInput($event.option.value, trigger, auto);">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>