簡體   English   中英

動態組件在 ViewInit 后加載時不起作用

[英]Dynamic Components not working when loaded after ViewInit

為什么下面的代碼不起作用? 為什么@ViewChildren無法檢測到ng-container

HTML

<div [innerHtml]="html"></div>

控制器:

import { Component, ViewChildren, AfterViewInit, QueryList,ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  @ViewChildren('helloComponent',{read: ViewContainerRef}) components: QueryList<ViewContainerRef>

  html = "<ng-container #helloComponent></ng-container><ng-container #helloComponent></ng-container>";

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver, 
    private injector: Injector
  ){

  }

  ngAfterViewInit() {
     var i = 0;
     this.components.forEach(hello => {
       const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
       var componentRef = hello.createComponent(componentFactory);
       componentRef.instance.name = i.toString();
        i++;
     });

  }
}

這是演示: https : //stackblitz.com/edit/angular-8-dynamic-components-not-working

@ViewChildren 應該指的是其中有孩子的父母:

<ng-container #helloComponents>
  <ng-container>
  </ng-container>
  <ng-container>
  </ng-container>
  <ng-container>
  </ng-container>
</ng-container>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM