可以说我想变得非常抽象和模块化,我想将组件作为输入传递给我的子组件。
那可能吗?
我知道我可以传递输入并在内部创建组件,但是有时我想传递不同的/组件,否则我将不得不为每个组件自定义代码,而我不能对操作进行抽象。
例如,假设我将组件P作为父对象,将C作为孩子,我对C这样的设计有特定的用途,并且我想在需要使用内部元素来实现此特定设计的任何时候都将C作为可重用的组件。
现在,如果我想让C(两个单独的元素)环绕两个不同的组件,我们将它们称为A和B。我希望P在创建它们到C之后能够将它们传递给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;
}
从不推荐使用的ComponentResolver答案中获得 启发
可以在此处找到答案
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句