可以说我想要变得非常抽象和模块化,并且我想将组件作为输入传递给我的子组件。
这可能吗?
我知道我可以传递输入并在内部创建组件,但有时我想传递不同的/组件,否则我必须为每个组件自定义代码,并且我无法抽象操作。
例如,假设我将组件 P 作为父组件,将 C 作为子组件,我对 C 这样的设计有特定的目的,并且我希望将 C 作为可重用组件,以便每当我想要实现此特定设计时里面有元素。
现在,如果我想让 C(两个独立的元素)包裹两个不同的组件,我们称它们为 A 和 B。我希望 P 在创建它们后能够将它们传递给 C,以保持设计抽象,同时能够只需将组件用作 C 内部的变量即可。
最佳答案
是的,这是可能的。实际上,这就是 Angular2 中模块化组件的组合方式。
例如,如果您有一个模态组件,并且希望在整个应用程序中使用它,但该组件只是一个包装器,需要向其中添加动态组件。
这是一个使用 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;
}
灵感来自deprecated ComponentResolver answer
另一种方法可以找到 answer HERE
关于angular - 在 Angular2 中传递组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381855/