Passing Components in Angular2

后端 未结 1 1463
一个人的身影
一个人的身影 2020-12-18 11:03

Lets say i wanna get very abstract and modular and i want to pass components as input to my child components.

Is that possible?

I understand that i can pass

相关标签:
1条回答
  • 2020-12-18 11:50

    Yes, it is possible. Actually is how composition for modular components works in Angular2.

    So for example if you have a modal component and you want to use that all over the app, but that component is just a wrapper and it is needed to add dynamic components to it.

    Here it's an example with the ComponentFactoryResolver :

    @Component({
      selector: 'my-dynamic-component',
      template: 'this is a dynamic injected component !'
    })
    export class MyDynamicComponent {}
    
    
    @Component({ 
      selector: 'wrapper',
      template: `
      <div>
        <p>Wrapper Component</p>
        <template #dynamicComponent></template> 
      </div>
      `
    })
    export class WrapperComponent {
      @Input() contentComponent: any;
      @ViewChild('dynamicComponent', { read: ViewContainerRef })
    
      dynamicComponent: any;
    
      constructor(private componentResolver: ComponentFactoryResolver) {}
    
      ngAfterViewInit():void {
        const factory = this.componentResolver.resolveComponentFactory(this.contentComponent);
    
        this.dynamicComponent.createComponent(factory);
      }
    }
    
    
    @Component({
      selector: 'my-app',
      template: ` 
      <wrapper [contentComponent]="MyDynamicComponent"></wrapper>`
    })
    export class AppComponent {
        MyDynamicComponent: any = MyDynamicComponent;
    }
    

    Inspired from deprecated ComponentResolver answer
    Another way of doing this can be found answer HERE

    Example PLUNKER

    0 讨论(0)
提交回复
热议问题