Angular ngFor循环下如何在HTML中绑定带索引的模板引用变量?
解决Angular2-Collapsible动态绑定详情模板的问题
问题的核心在于模板引用变量是静态解析的,你尝试的[detail]="'detail'+i"或者[attr.detail]="'detail'+i"都没法让Angular识别出对应的collapsible-table-row-detail实例——因为这些动态拼接的引用名在模板编译阶段并不存在,自然无法完成有效绑定。
下面是可行的解决方案:
步骤1:通过ViewChildren获取所有详情模板实例
首先在组件类中,使用@ViewChildren装饰器收集所有的collapsible-table-row-detail组件实例,这样我们就能通过索引精准匹配对应的行和详情:
import { Component, ViewChildren, QueryList } from '@angular/core'; import { CollapsibleTableRowDetailComponent } from 'angular2-collapsible'; @Component({ selector: 'your-component-selector', templateUrl: './your-component.component.html' }) export class YourComponent { details = [/* 你的业务数据数组 */]; // 收集所有标记为#detailRef的详情组件 @ViewChildren('detailRef') detailRefs: QueryList<CollapsibleTableRowDetailComponent>; }
步骤2:调整模板结构,循环绑定对应详情
修改模板,把每个collapsible-table-row和对应的collapsible-table-row-detail放在同一个循环上下文里,然后通过索引从detailRefs中获取对应的实例绑定到[detail]属性:
<collapsible-table [type]="'accordion'" borderedVertically="true" class="table"> <thead class="table-heading"> <collapsible-table-row> <th></th> <th>Reference ID</th> <th>Order ID</th> <th>OName</th> <th>FP</th> <th>SP</th> <th>Stat</th> <th>date</th> </collapsible-table-row> </thead> <tbody> <!-- 用ng-container包裹循环,避免生成多余DOM节点 --> <ng-container *ngFor="let item of details; let i = index"> <collapsible-table-row [detail]="detailRefs.toArray()[i]"> <td> <div class="input-group-text"> <input type="checkbox" aria-label="Checkbox for following text input"> </div> </td> <td (click)="showFirst=!showFirst"> <i class="material-icons" *ngIf="showFirst"> <span class="bulleticon"> - </span> </i> <i class="material-icons" *ngIf="!showFirst"> <span class="bulleticon"> + </span> </i> {{item.Reference_Id}}<br> </td> <td> {{item.OId}} </td> <td>{{item.OName}}</td> <td>{{item.FP}}</td> <td>{{item.SP}}</td> <td>{{item.Stat}} </td> <td>{{item.date}}</td> </collapsible-table-row> <!-- 每个行对应的详情模板,用#detailRef标记 --> <collapsible-table-row-detail #detailRef class="hidden-table"> <div class="container"> <div class="list col-5"> <span class="heading"> Order details </span> <ul class="unorderedlist"> <li> {{item.data1}} </li> <li> {{item.data2}} </li> <li> {{item.data3}}</li> </ul> </div> </div> </collapsible-table-row-detail> </ng-container> </tbody> </collapsible-table>
为什么这个方法有效?
@ViewChildren('detailRef')会自动收集所有带有#detailRef标记的组件实例,形成一个有序的QueryList。- 通过
detailRefs.toArray()[i],我们可以在循环中精确获取当前索引对应的详情组件实例,直接绑定到[detail]属性——这是Angular能够识别的合法绑定方式,完美适配动态循环场景。
内容的提问来源于stack exchange,提问作者Bharat Vk
相关产品推荐
相关产品推荐

