【问题标题】:Angular material autocomplete - make sure something is selected角度材料自动完成 - 确保选择了某些东西
【发布时间】:2021-05-16 03:56:31
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: angular autocomplete


    【解决方案1】:

    我不确定您在问什么,但如果您想确保选择了某个选项,请尝试添加 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

    【讨论】:

    • 只检查 INPUT 是否为空,我可以在其中输入任何内容来验证表单。我需要确保通过 MAT-AUTOCOMPLETE 选择了一个选项
    • 哦,好吧,我知道你想要什么了......我会更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2017-07-14
    • 2019-01-31
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多