Angular 为什么@ViewChildren仅第一次选择模板?

Angular 为什么@ViewChildren仅第一次选择模板?,angular,angular-components,viewchild,Angular,Angular Components,Viewchild,我正在创建一个应用程序,其中我希望使用组件渲染表中的按钮。因此,我创建了一个组件,保存了按钮模板,并使用@ViewChildren获取模板和ViewContainerRef将组件应用于模板。但是,只设置第一行,而不设置另一行。我想不出原因是什么? 以下是我一直在尝试的:不需要使用ComponentFactoryResolver注入动态组件。您可以使用他的标记名注入组件。我用一个有效的解决方案更新了stackblitz:您的解决方案不起作用,因为您对@ViewChild使用了一个引用,但您位于ng

我正在创建一个应用程序,其中我希望使用组件渲染表中的按钮。因此,我创建了一个组件,保存了按钮模板,并使用
@ViewChildren
获取模板和
ViewContainerRef
将组件应用于模板。但是,只设置第一行,而不设置另一行。我想不出原因是什么?
以下是我一直在尝试的:

不需要使用ComponentFactoryResolver注入动态组件。您可以使用他的标记名
注入组件。我用一个有效的解决方案更新了stackblitz:

您的解决方案不起作用,因为您对
@ViewChild
使用了一个引用,但您位于
ng For
中,因此您必须使用
@ViewChildren
管理
ViewContainerRef
查询列表

尝试按以下方式更改代码:

替换:

@ViewChild("dynamic", { static: false, read: ViewContainerRef }) ref;
@ViewChildren("dynamic") private button: QueryList<"dynamic">;
ngAfterViewInit() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(
      HelloComponent
    );
    const ref = this.ref.createComponent(componentFactory);
    
  }
与:

ngAfterViewInit(){
const targets=this.widgetTargets.toArray();
for(设i=0;i
这样我们就可以在参照列表上循环并动态创建组件


最好的。

当视图初始化时,当数据存在时,它工作得很好,但如果在获取
数据项时有延迟,则渲染
*ngIf
块时会有延迟,因此
@ViewChildren
无法获取模板。在这种情况下你能帮忙吗?也许你只需要订阅一个可观察的来源,顺便说一句,请添加一个新的问题,最好的
ngAfterViewInit() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(
      HelloComponent
    );
    const ref = this.ref.createComponent(componentFactory);
    
  }
ngAfterViewInit() {
    const targets = this.widgetTargets.toArray();
    for (let i = 0; i < targets.length; i++) {
        let target = targets[i];
        if(target) {
            let componentFactory = this._componentFactoryResolver.resolveComponentFactory(HelloComponent);
            let cmpRef: any = target.createComponent(componentFactory);
        }
    }
  }