Dynamically add Component in angular 2/4

前端 未结 3 2015
日久生厌
日久生厌 2021-01-07 03:29

How can I add component dynamically?

toolbar.component.ts:

@Component({
  selector: \'app-toolbar\',
  template: \'
3条回答
  •  一整个雨季
    2021-01-07 04:24

    Expose viewContainerRef on section.component.ts:

    @Component({
       selector: 'div[app-type=section]',
       template: ''
    })
    export class SectionComponent {
      @Input() active: boolean;
    
       constructor(public viewContainerRef: ViewContainerRef) { }
    } 
    

    Add an output to toolbar.component.ts:

    @Component({
      selector: 'app-toolbar',
      template: ''
    })
    export class ToolbarComponent {
      @Output() addComponentClick = new EventEmitter();
       constructor() { }
    } 
    

    In view.component.ts create a ComponentFactory for TextComponents to add them dynamically to active SectionComponents:

    import { Component, AfterViewInit, ViewChildren, QueryList, ElementRef, ComponentFactoryResolver, ComponentFactory, OnInit } from '@angular/core';
    import { TextComponent } from './text.component';
    import { SectionComponent } from './section.component';
    
    @Component({
       selector: 'app-view',
       template: `
    ` }) export class ViewComponent implements AfterViewInit, OnInit { @ViewChildren(SectionComponent) sections: QueryList; activeSections: SectionComponent[]; textComponentFactory: ComponentFactory; constructor(private componentFactoryResolver: ComponentFactoryResolver) { } ngOnInit() { this.textComponentFactory = this.componentFactoryResolver.resolveComponentFactory(TextComponent); } ngAfterViewInit() { this.activeSections = this.sections.reduce((result, section, index) => { if(section.active) { result.push(section); } return result; }, []); } onAddComponentClick() { this.activeSections.forEach((section) => { section.viewContainerRef.createComponent(this.textComponentFactory); }); } }

    StackBlitz example

提交回复
热议问题