【问题标题】:Allow user to type in only the options in mat-autocomplete in angular 6允许用户在角度 6 中仅输入 mat-autocomplete 中的选项
【发布时间】:2025-12-20 01:20:25
【问题描述】:

我正在使用 mat-autocomplete。

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

想知道是否有办法限制用户只能输入下拉菜单中提供的选项,即。仅一、二和三。当用户键入诸如 十六 之类的其他内容时,不应显示它

 export class AutocompleteSimpleExample {
  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
   ];

}

【问题讨论】:

  • 据我所知,这是当前的行为 - stackblitz.com/angular/yrjldemxkdb - 输入选项中没有的任何内容都不会显示下拉菜单...
  • 是的,但是有什么替代方案吗?

标签: angular mat-autocomplete


【解决方案1】:

您可以绑定到模糊事件并检查输入值是否等于所需的输入,如下所示。我在自己的自动编译上使用了类似的方法。

<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" (blur)="InputControl($event)" [matAutocomplete]="auto">

在组件中

InputControl(event) {
    setTimeout(() => {
        let isValueTrue = this.options.filter(myAlias =>
            myAlias  === event.target.value);
        if (isValueTrue.length === 0) {
            this.form.get(‘MyControl’).setValue(null);
        }
    }, 300);
}

【讨论】: