Angular2: Creating child components programmatically

后端 未结 5 1510
心在旅途
心在旅途 2020-12-13 18:20

Question

How to create child components inside a parent component and display them in the view afterwards using Angular2? How to make sure the injectables

5条回答
  •  情书的邮戳
    2020-12-13 18:28

    Programmatically add components to DOM in Angular 2/4 app

    We need to use ngAfterContentInit() lifecycle method from AfterContentInit. It is called after the directive content has been fully initialized.

    In the parent-component.html, add the a div like this:

    The parent-component.ts file looks like this:

    
    
    class ParentComponent implements AfterContentInit {
    
      @ViewChild("container", { read: ViewContainerRef }) divContainer
    
      constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
    
      ngAfterContentInit() {
        let childComponentFactory = this.componentFactoryResolver.resolveComponentFactory(childComponent);
        this.divContainer.createComponent(childComponentFactory);
        let childComponentRef = this.divContainer.createComponent(childComponentFactory);
        childComponentRef.instance.someInputValue = "Assigned value";
    
      }
    }
    

    Inside src\app\app.module.ts, add the following entry to the @NgModule() method parameters:

    
      entryComponents:[
        childComponent
      ],
    

    Notice that we're not accessing the div#container using the @ViewChild("container") divContainer approach. We need it's reference instead of the nativeElement. We will access it as ViewContainerRef:

    @ViewChild("container", {read: ViewContainerRef}) divContainer

    The ViewContainerRef has a method called createComponent() which requires a component factory to be passed as a parameter. For the same, we need to inject a ComponentFactoryResolver. It has a method which basically loads a component.

提交回复
热议问题