角度材料自动完成 - 确保选择了某些东西

时间:2021-05-16 03:56:31

标签: angular autocomplete

我正在使用角度材料自动完成功能,以允许用户从一长串列表中选择一家公司。

例如,它最初填充列表:Apple、Google、Microsoft 等,当用户键入“G”时,它仅过滤 Google。如何确保已选择其中一项?例如,即使有人只输入了“G”或“Google”,我的表单也可以提交,但除非有人实际单击列表中的“Google”,否则自动完成功能无法正确注册。除非从列表中选择实际选项(而不是文本类型到字段中),否则我可以使用某种类型的材料验证器或角度表单验证器来使表单无效吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

我不确定您要问什么,但如果您想确保选择了某个选项,请尝试添加 required 属性并在您的 ngAfterViewInit 中包含验证过程:

import { MatAutocompleteTrigger } from '@angular/material/autocomplete';
//....

  @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;

  ngAfterViewInit() {
    this.trigger.panelClosingActions.subscribe((e) => {
      if (!(e && e.source)) {
        this.myControl.setValue('');
        this.trigger.closePanel();
      }
    });
  }

在模板中:

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

工作demo