在 Angular2 中传递组件
Passing Components in Angular2
假设我想要非常抽象和模块化,我想将组件作为输入传递给我的子组件。
这可能吗?
我知道我可以传递输入并在内部创建组件,但有时我想传递 different/components 否则我将不得不为每个组件自定义代码而且我不能抽象操作。
例如,假设我将组件 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;
}
灵感来自
可以找到另一种方法
假设我想要非常抽象和模块化,我想将组件作为输入传递给我的子组件。
这可能吗?
我知道我可以传递输入并在内部创建组件,但有时我想传递 different/components 否则我将不得不为每个组件自定义代码而且我不能抽象操作。
例如,假设我将组件 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;
}
灵感来自
可以找到另一种方法