首页 > 解决方案 > 获取 mat-row angular 4 ViewContainerRef 的最佳方法

问题描述

我有一个 mat-table,现在我想获取单击行的 ViewContainerRef,以便我可以在该行中添加另一个组件。您能否告诉我获取行的 ViewContainerRef 的最佳方法。

目前我正在使用 ViewChildren 使用 myRow 作为 mat-row 的 ID 来获取它。

@ViewChildren("myRow", { read: ViewContainerRef }) containers;

我在单击该行时传递索引。

<mat-row #myRow *matRowDef="let row; columns: colInfo;let index=index" 
            (click)="expandRow(index, row)"></mat-row>

根据索引,我正在获取 ViewContainerRef 之类的

const container = this.containers.toArray()[index];

并创建如下所示的组件。

const factory = this.resolver.resolveComponentFactory(DetailTableComponent);
const component = container.createComponent(factory);  

如果我不在桌子上进行排序,它工作正常。一旦我执行排序,组件就会随机添加到不同的行,原因有两个:
1. 排序后索引会立即更新(它始终按行的顺序从 0 设置为 n)
2. ViewContainerRef 仍然拥有旧数据,即排序前的数据。

如果以上两个问题中的任何一个都解决了,那么我相信我的问题将得到解决。或者,如果我可以获得点击的 ViewContainerRef,那么我相信我的问题也会得到解决。

请帮忙。

标签: angulartypescript

解决方案


ViewContainerRef我也一直在努力解决如何从模板中获取特定内容。我现在能为您想到的最简单的解决方案:

改变这个

expandRow(index, row)

expandRow(index, row, myRow)

这将 myRow 作为 nativeElement 传递。

然后,而不是

const container = this.containers.toArray()[index];

const containers = this.containers.toArray();

从那里你应该能够进行查找以找到索引i在哪里

containers[i].element.nativeElement === myRow

推荐阅读