本文介绍了如何停止 mat-autocomplete 以将自定义用户输入值与给定选项分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 material.angular.io 中的 mat-auto 完整组件.默认行为是用户可以输入任何值,并提供可供选择的选项.您也可以将输入添加到所选值.您可以在此处查看示例.https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-简单-示例.html

I am using mat-auto complete component from material.angular.io. The default behavior is user can input any value as well as it gives options to choose from. Also you can add your input to chosen values.You can check example here.https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-simple-example.html

这是我用于生成自动完成输入字段的代码.

here is the code I am using for generating auto complete input field.

<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" disabled="true">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

但我希望表单字段仅从给定选项中获取值,并希望防止用户输入除给定选项之外的任何值.如何实现这一目标?这就像选择具有自动完成功能的输入.

But I want the form field to take only values from the given option and want to prevent from entering any values by users apart from given option. How to achieve this? It is like select input with auto complete feature.

推荐答案

github 它可能为那些最终来到这里的人提供一个简单的替代方案.

Found this solution on github it may provide a simple alternative to those who end up here.

创建自定义验证器:

private requireMatch(control: FormControl): ValidationErrors | null {
  const selection: any = control.value;
  if (this.options && this.options.indexOf(selection) < 0) {
    return { requireMatch: true };
  }
  return null;
}

将其附加到您的控件(我们需要将其绑定到 this 以便我们的验证器可以访问我们组件范围内的选项)

Attach it to your control (we need to bind it to this so that our validator can access our options in our component's scope)

  myControl = new FormControl(undefined, [Validators.required, this.requireMatch.bind(this)]);

可选择显示错误:

  <mat-error *ngIf="myControl.errors?.requireMatch">Value need match available options</mat-error>

这里的例子-----------> https://stackblitz.com/编辑/angular-hph5yz

Example here -----------> https://stackblitz.com/edit/angular-hph5yz

这篇关于如何停止 mat-autocomplete 以将自定义用户输入值与给定选项分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-25 22:42