[英]Angular 7 resolve component factory from selector
我正在开发一个Angular 7 lib,它知道以前声明的组件(在相同或更高的模块中)。 我此时只有组件选择器,并希望在容器视图中创建该组件。
可以这样做吗? 我可以从编译器内部工厂获得工厂而无需维护自己的注册表吗?
谢谢
如果您可以获得声明组件的模块以及组件的选择器,则下面的方法将起作用。
首先,创建一个辅助方法来从类型中获取装饰器注释(我不相信这将适用于IE或aot编译):
/**
* gets a decorator of the requested type off of the given decorated type
* @param decoratedType to get decorator annotations off of
* @param decoratorType to search for out of all the decorators on decoratedType
* @returns decorator from the decoratedType of the decoratorType
*/
export function decoratorOfType<T>(decoratedType: Type<any>, decoratorType: Type<T>): T {
// get all decorators off of the provided type
return Reflect.getOwnPropertyDescriptor(decoratedType, '__annotations__').value.find((annotation: any) =>
// get the decorator that matches the requested type
annotation instanceof decoratorType
);
}
这个函数可以很容易地获得声明组件的模块的@NgModule装饰器(在我的例子中是AppModule
):
const ngModuleDecorator = decoratorOfType(AppModule, NgModule);
使用模块装饰器,您可以查看其声明并找到@Component装饰器和选择器设置为您要查找的内容(在我的示例中为app-counter
)。
const componentType = ngModuleDecorator.declarations.find((declaration: Type<any>) => {
// get the @Component decorator
const declarationDecorator = decoratorOfType(declaration, Component);
// find a declaration with the @Component decorator (not a @Directive) with the requested selector
return declarationDecorator != null && declarationDecorator.selector === 'app-counter';
});
拥有组件类型后,您可以使用ViewContainerRef和ComponentFactoryResolver创建组件,就像其他教程向您展示如何动态创建组件一样:
// get the component factory using the component type
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentType as Type<any>);
// fill the content using the component factory
this.dynamicContentDiv.clear();
this.dynamicContentDiv.createComponent(componentFactory);
我在StackBlitz上创建了一个工作示例,它根据所选的选择器在两个组件之间切换:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.