Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

angular - Passing Components in Angular2

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 the inputs and create the component internally, but sometimes i want to pass different/components otherwise i would have to customize the code to each component and i can't be abstract about the operation.

For Example, lets say i have component P as a parent and C as a child, i have a certain purpose for C such design and i would like to have C as a reusable component for whenever i want to implement this certain design with elements inside.

Now if i want to have C (two separate elements) wrap around two different components let's call them A & B. i want P to be able to pass them after creating them to C to keep the design abstract while being able to just use the components as a variable inside C.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...