如何使用 mat-autocomplete 完全重置 mat-input

And*_*ico 5 angular-material angular

在这个Stackblitz中,我有一个带有异步数据的 mat-autocomplete。

(optionSelected)触发时(当我单击一个选项时),我希望该字段完全重置,就像它刚刚渲染/初始化一样。

目前这个解决方案有两个问题

  1. 清除后我没有得到任何自我暗示。我想再次获得完整的自我暗示。

==> 我确实必须再次模糊并聚焦或开始打字。

  1. 当我打字而只是模糊重新聚焦时,我仍然将mat-option.mat-selected类附加到面板,因为重置只影响输入值。我用 突出显示了这一点background-color: red;

小智 8

您需要将重置功能设置为如下所示

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

在你的 HTML 代码中将是

<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>
Run Code Online (Sandbox Code Playgroud)