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

如何基于索引实现MatAutocompleteTrigger的面板联动触发(表格场景)

表格中MatAutocomplete联动问题解决方案

Sample Table View

需求与问题

  • 需求:表格场景下,选中某行的workItem自动完成下拉选项时,自动打开该行对应的activity自动完成下拉面板。
  • 当前问题:无论选中哪一行的workItem,始终只打开第一行的activity下拉面板。

问题原因

@ViewChild只会获取DOM中第一个匹配的元素,表格是循环渲染多组下拉框,所以无法定位到当前行对应的activity触发器。

解决方案

改用@ViewChildren获取所有下拉触发器实例,结合行索引定位到当前行的activity组件,实现联动。

修改后的index.ts代码

import { Component, ViewChildren, QueryList } from '@angular/core';
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';

@Component({
  selector: 'your-component-selector',
  templateUrl: './index.html'
})
export class YourComponent {
  @ViewChildren('workItemInput') workItemInputs: QueryList<MatAutocompleteTrigger>;
  @ViewChildren('activityInput') activityInputs: QueryList<MatAutocompleteTrigger>;
  data: any[] = []; // 表格数据,根据业务定义结构

  onWorkItemChanged(rowIndex: number) {
    setTimeout(() => {
      const activityTrigger = this.activityInputs.toArray()[rowIndex];
      activityTrigger?.openPanel();
    });
  }
}

修改后的index.html代码

<table>
  <tr *ngFor="let row of data; let i = index">
    <td>
      <input #workItemInput matInput [matAutocomplete]="workItemAuto" [(ngModel)]="row.workItem"/>
      <mat-autocomplete [disableRipple]="true" #workItemAuto="matAutocomplete" (optionSelected)="onWorkItemChanged(i)">
          <mat-option [value]="item.trim()" *ngFor="let item of filteredWorkItemOptions" (click)="checkWorkItemType()">
              {{item}}
          </mat-option>
      </mat-autocomplete>
    </td>
    <td>
      <input #activityInput matInput [matAutocomplete]="activityAuto" [(ngModel)]="row.activity" />
      <mat-autocomplete [disableRipple]="true" #activityAuto="matAutocomplete">
          <mat-option [value]="item.trim()" *ngFor="let item of filteredActivityptions" (onSelectionChange)="onSelFunc()" (click)="checkForChange()">
              {{item}}
          </mat-option>
      </mat-autocomplete>
    </td>
  </tr>
</table>

关键说明

  1. @ViewChildren替代@ViewChild:获取所有同名模板变量的实例,存储为QueryList,通过toArray()转为数组方便按索引访问。
  2. 传递行索引:在表格行循环中添加let i = index,并在workItem的optionSelected事件中传入索引,定位到当前行。
  3. 唯一模板变量:每个mat-autocomplete使用独立的模板变量(如workItemAuto、activityAuto),避免重复变量导致的DOM元素冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:32:09