如何使用mat-autocomplete完全重置mat-input [英] How to fully reset mat-input with mat-autocomplete

查看:204
本文介绍了如何使用mat-autocomplete完全重置mat-input的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处 Stackblitz 我有一个带有异步数据的mat-autocomplete.

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

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

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

当前此解决方案存在两个问题

  1. 通关后,我没有得到任何自动建议.我想再次获得完整的自动建议.

==>我必须再次模糊并聚焦或开始输入.

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

  1. 当我不要键入并且只是模糊重新聚焦时,自重置后,我仍然在面板上附加了mat-option.mat-selected类只会影响输入值.我用background-color: red;突出了这一点.
  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;.

推荐答案

您需要使重置功能类似于以下

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

,并且在您的HTML代码中将是

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>

这篇关于如何使用mat-autocomplete完全重置mat-input的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆