在Angular2中传递组件 [英] Passing Components in Angular2

查看:79
本文介绍了在Angular2中传递组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我想变得非常抽象和模块化,我想将组件作为输入传递给子组件.

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

有可能吗?

我了解我可以在内部传递输入并创建组件,但是有时我想传递不同的/组件,否则我将不得不为每个组件自定义代码,而我不能对操作进行抽象.

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.

例如,假设我将组件P作为父级,而将C作为孩子,我对C这样的设计有特定的目的,并且我希望在每次要实现此特定设计的情况下都将C作为可重用的组件里面有元素.

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.

现在,如果我想让C(两个单独的元素)环绕两个不同的组件,我们将它们称为A& ;; B.我希望P在将它们创建到C之后能够将它们传递给C,以保持设计抽象,同时能够仅将组件用作C中的变量.

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.

推荐答案

是的,有可能.实际上,模块化组件的组合是如何在Angular2中工作的.

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.

这里是 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

示例PLUNKER

这篇关于在Angular2中传递组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆