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

求助:Angular Material Autocomplete多输入框仅显示单个数组问题

解决Angular Material Autocomplete多输入框共用数据的问题

嘿,我看了你的问题场景,一下子就找到问题根源啦!你现在遇到的多个输入框表现得像同一个的问题,核心原因是所有Autocomplete组件共用了同一个FormControl实例和同一组过滤后的选项数据——不管你在哪个输入框输入,触发的都是同一个过滤逻辑,自然显示的都是同一套结果。

下面给你一步步的修复方案:

1. 为每个输入框创建独立的FormControl

别再只声明一个通用的FormControl啦,给每个需要Autocomplete的输入框单独创建实例:

// 组件类里的代码
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

// 比如你有两组不同的选项数据,对应两个输入框
foodControl = new FormControl();
animalControl = new FormControl();

// 原始选项数组示例
foods: string[] = ['Pizza', 'Burger', 'Fries'];
animals: string[] = ['Cat', 'Dog', 'Bird'];

2. 为每个输入框创建独立的过滤数据流

每个输入框的过滤结果应该是独立的Observable,我们可以把过滤函数改成通用的,接收不同的原始数组参数:

filteredFoods$: Observable<string[]>;
filteredAnimals$: Observable<string[]>;

ngOnInit() {
  // 食物输入框的过滤逻辑
  this.filteredFoods$ = this.foodControl.valueChanges.pipe(
    startWith(''),
    map(value => this._filter(value, this.foods))
  );

  // 动物输入框的过滤逻辑
  this.filteredAnimals$ = this.animalControl.valueChanges.pipe(
    startWith(''),
    map(value => this._filter(value, this.animals))
  );
}

// 通用过滤函数,接收输入值和要过滤的原始数组
private _filter(value: string, options: string[]): string[] {
  const filterValue = value.toLowerCase();
  return options.filter(option => option.toLowerCase().includes(filterValue));
}

3. 在模板中绑定对应的控件和数据流

每个输入框要绑定自己的FormControl,Autocomplete也要对应自己的过滤Observable,注意模板引用变量(比如#autoFood、#autoAnimal)也要区分开:

<!-- 食物输入框的Autocomplete -->
<mat-form-field>
  <input 
    type="text" 
    placeholder="选择食物" 
    aria-label="Food" 
    matInput 
    [formControl]="foodControl" 
    [matAutocomplete]="autoFood"
  >
  <mat-autocomplete #autoFood="matAutocomplete">
    <mat-option *ngFor="let option of filteredFoods$ | async" [value]="option">
      {{ option }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

<!-- 动物输入框的Autocomplete -->
<mat-form-field>
  <input 
    type="text" 
    placeholder="选择动物" 
    aria-label="Animal" 
    matInput 
    [formControl]="animalControl" 
    [matAutocomplete]="autoAnimal"
  >
  <mat-autocomplete #autoAnimal="matAutocomplete">
    <mat-option *ngFor="let option of filteredAnimals$ | async" [value]="option">
      {{ option }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

这样改完之后,每个输入框就会独立维护自己的输入状态和过滤结果,再也不会出现“共用数据”的问题啦~

内容的提问来源于stack exchange,提问作者A. B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:13:06