You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何校验mat-autocomplete组合框输入是否在可选选项内并给出警告

Angular Material 组合框非法输入警告实现方案

实现步骤:

  • 第一步:组件TS逻辑调整
    你需要先保留完整的原始可选机型列表(不要只用过滤后的filteredAircraftTypes作为比对源),给aircraftType表单控件添加自定义验证器,判断当前输入值是否在可选范围内:
import { AbstractControl, Validators } from '@angular/forms';

// 先定义全量可选机型列表,和你用来生成filteredAircraftTypes的数据源保持一致
allAircraftTypes: {label: string, [key: string]: any}[] = [];

// 表单组初始化时添加自定义验证器
this.yourFormGroup = this.fb.group({
  // 其他表单控件逻辑保留
  aircraftType: ['', [Validators.required, this.aircraftTypeValidator]]
})

// 自定义机型合法性验证器
aircraftTypeValidator = (control: AbstractControl) => {
  const inputValue = control.value;
  // 兼容两种取值场景:选中下拉项返回对象、手动输入返回字符串
  const inputLabel = typeof inputValue === 'object' ? inputValue?.label : inputValue?.trim();
  if (!inputLabel) return null;
  // 比对全量列表判断输入是否合法
  const isValid = this.allAircraftTypes.some(item => item.label === inputLabel);
  return isValid ? null : { invalidAircraftType: true };
}

// 原有输入变更回调里手动触发验证,保证实时性
onAircraftTypeChange() {
  this.yourFormGroup.get('aircraftType')?.updateValueAndValidity();
  // 你原来的下拉选项过滤逻辑保留即可
  // ...原有过滤代码
}
  • 第二步:模板添加警告提示
    在现有mat-form-field组件内新增mat-error节点,验证不通过时自动展示警告:
<mat-form-field appearance="outline" class="width-1">
  <mat-label>Aircraft Type (ICAO)</mat-label>
  <!-- test autocomplete aircraft type -->
  <input
    type="text"
    placeholder="Aircraft Type (ICAO)"
    aria-label="Aircraft Type (ICAO)"
    matInput
    formControlName="aircraftType"
    [matAutocomplete]="type"
    (input)="onAircraftTypeChange()"
  />
  <span matSuffix class="down">
    <mat-icon>arrow_drop_down</mat-icon>
  </span>
  <mat-autocomplete
    #type="matAutocomplete"
    (optionSelected)="onSelectAircraftType($event.option.value)"
    [displayWith]="displayAircraftTypeFn"
  >
    <mat-option
      *ngFor="let type of filteredAircraftTypes | async"
      [value]="type"
    >
      {{ type.label }}
    </mat-option>
  </mat-autocomplete>
  <!-- 新增非法输入警告 -->
  <mat-error *ngIf="yourFormGroup.get('aircraftType')?.hasError('invalidAircraftType')">
    输入的机型代码不在可选范围内,请从下拉列表选择
  </mat-error>
  <!-- end test autocomplete -->
</mat-form-field>

如果需要更醒目的提示效果,可以在mat-error节点内加入warning样式的Material图标,配合默认的红色错误样式即可符合警告的视觉要求。如果你的displayWith函数返回值不是label字段,只需对应调整验证器内的取值逻辑即可。

内容的提问来源于stack exchange,提问作者Rence Sacramento

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:09:04