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

Angular 16中Mat-Chips结合Autocomplete功能失效求助

Angular 16 Mat-Chips 自动补全失效问题修复方案

针对你遇到的Mat-Chips自动补全过滤无效问题,以下是关键错误点及修复代码:

1. 下拉选项显示错误

HTML中mat-option的文本绑定错误,item是Participantes类型,nome属性嵌套在funcionario对象下,需修正显示逻辑:

<mat-option *ngFor="let item of filteredParticipantes$| async" [value]="item">
  {{item.funcionario.nome}}
</mat-option>

2. FormControl 未正确初始化

确保participantesControle正确关联表单控件,在组件类中补充:

// 表单初始化时添加participantesCtrl控件
this.form = this._fb.group({
  participantesCtrl: [null],
  // 其他表单字段...
});

// 定义表单控件引用
participantesControle = this.form.get('participantesCtrl') as FormControl<string | null>;

3. Add 函数逻辑错误

原代码获取输入值方式错误,且对象存在性判断失效,修复后:

public add(event: MatChipInputEvent): void {
  const value = (event.value || '').trim();
  if (value) {
    // 通过名称判断是否已存在该参与者
    const exists = this.allParticipantes.some(p => 
      p.funcionario.nome.toLowerCase() === value.toLowerCase()
    );
    if (!exists) {
      // 根据实际场景构造Funcionario对象,可从服务匹配或临时创建
      const funcionario: Funcionario = { nome: value /* 补充其他属性 */ };
      const participanteIndividual: Participantes = {
        funcionario,
        codParticipantes: 0,
        codReservaSala: 0
      };
      this.allParticipantes.push(participanteIndividual);
    }
  }
  event.chipInput!.clear();
  this.participantesControle.setValue(null);
}

4. Filter 函数与Observable优化

  • 确保allParticipantes在组件初始化时已加载数据源(比如从_funcionarioService获取)
  • 优化过滤逻辑,可选排除已选中的参与者:
public filter(value: string): Participantes[] {
  const filterValue = value.toLowerCase();
  return this.allParticipantes.filter(participante => 
    participante.funcionario.nome.toLowerCase().includes(filterValue) &&
    // 可选:避免重复添加已选中的参与者
    !this.allParticipantes.some(p => p.funcionario.nome === participante.funcionario.nome)
  );
}

// 组件构造函数中修正Observable逻辑
constructor(/* 依赖注入 */) {
  this.filteredParticipantes$ = this.participantesControle.valueChanges.pipe(
    startWith(''),
    debounceTime(150), // 降低过滤频率,提升性能
    map((part: string | null) => {
      const filterValue = part?.toLowerCase() || '';
      return filterValue ? this.filter(filterValue) : this.allParticipantes.slice();
    })
  );
}

5. Selected 函数逻辑修正

修正对象赋值逻辑,避免重复添加:

public selected(event: MatAutocompleteSelectedEvent): void {
  const selectedParticipante = event.option.value as Participantes;
  const exists = this.allParticipantes.some(p => 
    p.funcionario.nome === selectedParticipante.funcionario.nome
  );
  if (!exists) {
    this.allParticipantes.push(selectedParticipante);
  }
  this.participantesControle.setValue(null);
  this.participantesInput.nativeElement.value = '';
}

内容的提问来源于stack exchange,提问作者Rafaela Repessold

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:13:18