Angular 如何从ViewContainerRef.get()获取动态创建的组件的组件实例
我要完成的工作的总结Angular 如何从ViewContainerRef.get()获取动态创建的组件的组件实例,angular,dynamic,viewchildren,Angular,Dynamic,Viewchildren,我要完成的工作的总结 将组件动态添加到ViewContainerRef(完成) 使用属性初始化这些动态组件(完成) 获取对动态创建的组件实例的访问权限,以便我可以根据实际情况做出决策 问题 动态添加组件时,它们将添加到ViewContainerRef ViewContainerRef提供返回ViewRef的方法,如get(index) ViewRef似乎与组件实例没有任何关系,这使得获取所需数据成为一项挑战 工作代码如下所示(用于动态创建组件) appComponent首先使用Compo
- 将组件动态添加到
(完成)ViewContainerRef
- 使用属性初始化这些动态组件(完成)
- 获取对动态创建的组件实例的访问权限,以便我可以根据实际情况做出决策
- 动态添加组件时,它们将添加到
ViewContainerRef
提供返回ViewContainerRef
的方法,如ViewRef
get(index)
似乎与ViewRef
实例没有任何关系,这使得获取所需数据成为一项挑战组件
appComponent
首先使用ComponentFactoryResolver
创建几个组件,并将它们添加到模板中定义的ViewChild
。每个DynamicComponent
都使用一个id
属性值进行初始化,我们在创建后尝试引用该属性值
@Component({
selector: "my-app",
template: `
<h3>Retrieving Component Reference for Dyamic Compnents</h3>
<button (click)="getCompRef()">Get References</button>
<div>
<ng-container #childCont></ng-container>
</div>
<div>
<small>List out the Ids from the dynamic components</small> <br />
{{ createdItemIds | json }}
</div>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
@ViewChild("childCont", { read: ViewContainerRef })
childCont: ViewContainerRef;
createdItemIds: string[] = [];
itemLimit = 5;
constructor(
private fr: ComponentFactoryResolver,
private cdr: ChangeDetectorRef
) {}
ngAfterViewInit(): void {
for (let i = 0; i < this.itemLimit; i++) {
const factory = this.fr.resolveComponentFactory(DynamicComponent);
const compRef = this.childCont.createComponent(factory, i);
// Set the id of the instance so that we can use it later
compRef.instance.id = i + 1;
this.cdr.detectChanges();
}
}
...
}
到目前为止一切都很好
- 组件是动态创建的
- 组件实例用ID初始化,我们可以通过显示在UI中的fat看到ID
AppComponent
中,当用户单击该按钮时,将调用getCompRef()
方法,并通过childCont(ViewContainerRef)
getCompRef():void{
for(设i=0;i
但是,从ViewContainerRef.get()
返回的ViewRef
是ChangeDetectoreRef
的子类,不包含任何对所讨论实例的引用
在对这个问题进行研究时,它尝试使用ViewChildren
来获取正在创建的列表组件,但由于以下问题而无法工作:
- 或示例假定
视图子对象
选择器
中使用的指令用于模板中预定义的组件
- 我看到一些人在使用
时希望获得ViewRef,对此我有很多疑问,但在这种情况下,这是没有帮助的Component.instance
- 有没有一种简单的方法可以从我缺少的
获取组件实例ViewRef
谢谢。查看儿童应该能够获取给定类型的所有儿童,您尝试过吗?是的,我尝试过使用
@ViewChildren(DynamicComponent)children:QueryList
但queryList始终为空,并且从不包含已添加的组件。这意味着当收集列表时,组件还不存在或永远不存在。必须查看afterViewInit或更高版本之后的子级才能查看渲染内容。如果它们没有显示,则1)指定了错误的类型2)它们没有显示或3)其他内容。将实例添加到dom时,为什么不将实例存储在变量中或将所有动态实例存储在映射中<代码>compRef.instance.id=i+1代码>您已经在此行访问了实例。除了一些不稳定的解决方案外,无法从ViewRef获取实例。在创建动态组件时将实例存储在某个位置,以后再使用该存储
@Component({
selector: "dynamic-component",
template: `
<div>Dynamic Component: {{ id }}</div>
`,
styles: [``]
]
})
export class DynamicComponent {
id: number;
}
getCompRef(): void {
for (let i = 0; i < this.itemLimit; i++) {
const viewRef = this.childCont.get(i);
// How do I get at the instance of the view in order to obtain id?
// the view Ref doesn't provide access to the instance
// console.log(viewRef);
}
}