3

如何动态添加组件?

工具栏.component.ts:

@Component({
  selector: 'app-toolbar',
  template: '<button>Add Text component</button>'
})
export class ToolbarComponent {
   constructor() { }
}  

section.component.ts:

@Component({
   selector: 'div[app-type=section]',
   template: ''
})
export class SectionComponent {
   constructor() { }
}  

text.component.ts:

@Component({
   selector: 'app-text',
   template: '<p>This is dynamically component</p>'
})
export class TextComponent {
   constructor() { }
}  

view.component.ts:

@Component({
   selector: 'app-view',
   template: `<div class="container">
<app-toolbar></app-toolbar>
<div app-type="section" id="SECTION1" class="active"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class SectionComponent {}

当我单击 ToolBarComponent 时,我想将 TextComponent 添加到具有“活动”类的 SectionComponent 中。

4

3 回答 3

10

viewContainerRefsection.component.ts上公开:

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

   constructor(public viewContainerRef: ViewContainerRef) { }
} 

将输出添加到toolbar.component.ts

@Component({
  selector: 'app-toolbar',
  template: '<button (click)="addComponentClick.emit()">Add Text component</button>'
})
export class ToolbarComponent {
  @Output() addComponentClick = new EventEmitter();
   constructor() { }
} 

view.component.tsComponentFactory中为 TextComponents创建一个以将它们动态添加到活动的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: `<div class="container">
<app-toolbar (addComponentClick)="onAddComponentClick()"></app-toolbar>
<div app-type="section" id="SECTION1" [active]="true"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class ViewComponent implements AfterViewInit, OnInit {
  @ViewChildren(SectionComponent) sections: QueryList<SectionComponent>;
  activeSections: SectionComponent[];
  textComponentFactory: ComponentFactory<TextComponent>;

  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 示例

于 2018-03-03T15:15:11.840 回答
2

我有另一种方法,请检查你的情况

html
<ng-container *ngComponentOutlet="COMPONENT"></ng-container>

.ts
import { COMPONENT } from './..dir../component'

或者

html
<ng-container *ngComponentOutlet="option.component"></ng-container>

.ts
import { COMPONENT } from './..dir../component'    
option = {
  component: COMPONENT
}

或者如果它是动态的,则将组件添加到entryComponent

app.module.ts
import { COMPONENT } from './..dir../component'
@NgModule({
   declarations: [COMPONENT],
   /.
   ..
   ..
  ./
  entryComponents: [COMPONENT]
});    

html
<ng-container *ngComponentOutlet="option.component"></ng-container>

.ts
/** The COMPONENT is not imported since it is added to entrycomponent**/
@Input() option;
于 2019-02-21T08:05:03.567 回答
2

我会使用 ngFor view.component.ts 来做到这一点

@Component({
   selector: 'app-view',
   template: `
     <div class="container">
       <app-toolbar (addEvent)="addEvent($event)"></app-toolbar>
       <div app-type="section" id="SECTION1" class="active">
          <app-text *ngFor="let appText in textArray"></app-text>
       </div>
       <div app-type="section" id="SECTION2"></div>
     </div>
   `
})
export class SectionComponent {
   public textArray: string[] = [];
   public addEvent(event: string) : void {
      textArray.push(event);
   }
   ....
}

工具栏.component.ts:

import { Component, EventEmitter, Output } from '@angular/core';
@Component({
  selector: 'app-toolbar',
  template: '<button (click)="addNewText()">Add Text component</button>'
})
export class ToolbarComponent {
   @Output addEvent: EventEmitter<string> = new EventEmitter();
   constructor() { }
   addNewText(): void {
      this.addEvent.emit("");
   }
   ....
}  
于 2018-03-03T05:55:59.333 回答