问题描述
我要完成的工作总结
问题
- 动态添加组件时,会将它们添加到
ViewContainerRef
-
ViewContainerRef
提供了返回get(index)
的方法,例如ViewRef
。 -
ViewRef
与Component
实例似乎没有任何关系,这对于获取所需数据来说是一个挑战
Here is a Stackblitz Link,下面显示工作代码(用于动态创建组件)
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();
}
}
...
}
要添加的DynamicComponent
非常简单。为简化起见,它仅包含一个我们试图获取的id
属性
@Component({
selector: "dynamic-component",template: `
<div>Dynamic Component: {{ id }}</div>
`,styles: [``]
]
})
export class DynamicComponent {
id: number;
}
到目前为止一切都很好。
- 组件是动态创建的
- 使用ID初始化组件实例,通过显示在UI中的胖图标我们可以看到它
问题来自尝试从DynamicallyCreated组件中检索ID属性。
在AppComponent
中,当用户单击按钮时,将调用getCompRef()
方法并遍历childCont (ViewContainerRef)
的每个子对象
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);
}
}
然而,从ViewRef
返回的ViewContainerRef.get()
是ChangeDetectoreRef
的子类,并且不包含对所讨论实例的任何引用。
在对此问题进行研究时,它尝试使用ViewChildren
来获取正在创建的列表组件,但这由于诸如此类的问题而无法正常工作
- https://github.com/angular/angular/issues/8785
- 或示例假定
ViewChildren
selector
中使用的指令是针对已在模板中预定义的组件的。 - 对于一些希望拥有
Component.instance
的人获得ViewRef的人,我看到了很多问题,但这在这种情况下没有帮助。
最终我的问题是,
感谢您的帮助。
谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)