【问题标题】:Why does @ViewChildren pick the template only for the first time?为什么@ViewChildren 只第一次选择模板?
【发布时间】:2020-02-10 03:13:36
【问题描述】:

我正在创建一个应用程序,我想在其中使用组件呈现表格内的按钮。因此,我创建了一个组件,其中保留了按钮模板,并使用@ViewChildren 获取模板并使用ViewContainerRef 将组件应用于模板。但是,只有第一行被设置,而不是另一行。我想不通这是什么原因? 这是我一直在尝试的:https://stackblitz.com/edit/angular-rsxvbt

【问题讨论】:

    标签: angular angular-components viewchild


    【解决方案1】:

    您的解决方案不起作用,因为您使用带有 @ViewChild 的单个引用,但您位于 ng-For 内,因此您必须使用 @ViewChildren 管理 ViewContainerRefQueryList

    尝试如下更改您的代码:

    替换:

    @ViewChild("dynamic", { static: false, read: ViewContainerRef }) ref;
    @ViewChildren("dynamic") private button: QueryList<"dynamic">;
    

    与:

    @ViewChildren('dynamic', {read: ViewContainerRef}) public widgetTargets: QueryList<ViewContainerRef>;
    

    这样我们就可以对每个孩子都有一个 ref

    替换:

    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);
            }
        }
      }
    

    这样我们就可以循环遍历我们的 refs 列表并动态创建我们的组件

    stackblitz

    一切顺利。

    【讨论】:

    • 好吧,当视图初始化时数据存在时它工作得很好,但是如果在获取 dataItems 时有延迟,那么渲染 *ngIf 块会有延迟,结果是 @ViewChildren无法获取模板。在这种情况下你能帮忙吗?
    • 可能您只是订阅了一个可观察的来源,顺便说一句,请添加一个新问题,一切顺利
    【解决方案2】:

    不需要使用 ComponentFactoryResolver 注入动态组件。您可以使用他的标签名称&lt;hello&gt;&lt;/hello&gt; 来注入您的组件。我用一个可行的解决方案更新了你的 stackblitz:https://stackblitz.com/edit/angular-qbbewn

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 2019-11-18
      • 2020-09-09
      • 2021-03-20
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      相关资源
      最近更新 更多