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

查看:41
本文介绍了如何使用 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天全站免登陆