How to place a dynamic component in a container

前端 未结 3 1115
面向向阳花
面向向阳花 2020-12-01 03:26

I want to create dynamic components and insert views of these components to a container.

I think this can be achieved by ViewContainerRef.

But I don\'t know,

3条回答
  •  失恋的感觉
    2020-12-01 04:12

    You can get the ViewContainerRef of the current component by or from an element in the view of the current component

    @Component({
      selector: '...',
      directives: [OtherComponent, FooComponent],
      template: `
        
        
        
    ` }) export class SomeComponent { // `ViewContainerRef` from an element in the view @ViewChild(OtherComponent, {read: ViewContainerRef}) other; @ViewChild('foo', {read: ViewContainerRef}) foo; @ViewChild('div', {read: ViewContainerRef}) div; // `ViewContainerRef` from the component itself constructor(private viewContainerRef:ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {} let factory = this.componentFactoryResolver.resolveComponentFactory(ControlBox) this.componentRef = this.other.createComponent(factory); // this.componentRef = this.foo.createComponent(factory); // this.componentRef = this.div.createComponent(factory); // this.componentRef = this.viewContainerRef.createComponent(factory); }); }

    See also Angular 2 dynamic tabs with user-click chosen components

提交回复
热议问题