我目前正在使用以下代码在我的应用程序中动态加载角度组件。
currentSpec
这里resolveComponentFactory函数接受组件类型。我的问题是,有没有办法可以使用组件名称字符串加载组件,例如我将组件定义为
export class WizardTabContentContainer {
@ViewChild('target', { read: ViewContainerRef }) target: any;
@Input() TabContent: any | string;
cmpRef: ComponentRef<any>;
private isViewInitialized: boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {
}
updateComponent() {
if (!this.isViewInitialized) {
return;
}
if (this.cmpRef) {
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.TabContent);
this.cmpRef = this.target.createComponent(factory);
}
}
如何使用组件名称字符串添加上述组件&#34; MyComponent&#34;而不是类型?
答案 0 :(得分:31)
也许这会起作用
import { Type } from '@angular/core';
@Input() comp: string;
...
const factories = Array.from(this.resolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);
其中this.comp
是您的组件的字符串名称,如"MyComponent"
<强> Plunker Example 强>
要使用缩小功能,请参阅
答案 1 :(得分:4)
我知道这篇文章很老,但是Angular发生了很多变化,从易用性和安全性上来说,我真的不喜欢任何解决方案。这是我的解决方案,希望您喜欢它。我不会显示用于实例化该类的代码,因为上面的示例和原始Stack Overflow问题已经显示了解决方案,并且实际上是在询问如何从Selector中获取Class实例。
export const ComponentLookupRegistry: Map<string, any> = new Map();
export const ComponentLookup = (key: string): any => {
return (cls) => {
ComponentLookupRegistry.set(key, cls);
};
};
将上述Typescript装饰器和Map放置在您的项目中。您可以像这样使用它:
import {ComponentLookup, ComponentLookupRegistry} from './myapp.decorators';
@ComponentLookup('MyCoolComponent')
@Component({
selector: 'app-my-cool',
templateUrl: './myCool.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyCoolComponent {...}
下一步,这很重要,您需要将组件添加到模块中的entryComponents
。这样,在应用启动过程中就可以调用Typescript装饰器。
现在,当您拥有类引用时,现在在代码中要使用动态组件的任何地方(如上面的几个示例),您都可以从地图中获取它。
const classRef = ComponentLookupRegistry.get('MyCoolComponent');
// Returns a reference to the Class registered at "MyCoolComponent
我真的很喜欢这种解决方案,因为您注册的KEY可以是组件选择器,也可以是对您很重要或在服务器中注册的其他重要内容。在我们的案例中,我们需要一种让服务器告诉我们要加载到仪表板中的组件(按字符串)的方法。
答案 2 :(得分:0)
也可以通过导入:
进行访问someComponentLocation.ts - 包含可能组件的枚举:
export * from './someComponent1.component'
export * from './someComponent2.component'
export * from './someComponent3.component';
导入程序组件:
import * as possibleComponents from './someComponentLocation'
...
@ViewChild('dynamicInsert', { read: ViewContainerRef }) dynamicInsert: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver){}
然后您可以创建组件实例,例如:
let inputComponent = possibleComponents[componentStringName];
if (inputComponent) {
let inputs = {model: model};
let inputProviders = Object.keys(inputs).map((inputName) => { return { provide: inputName, useValue: inputs[inputName] }; });
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
let injector: ReflectiveInjector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicInsert.parentInjector);
let factory = this.resolver.resolveComponentFactory(inputComponent as any);
let component = factory.create(injector);
this.dynamicInsert.insert(component.hostView);
}
请注意,组件必须位于@NgModule entryComponents
中答案 3 :(得分:0)
答案 4 :(得分:0)
其他方法可能对您有所帮助。
1。首先定义一个用作名称映射组件的类,并将moduleNmap nmc用作类RegisterNMC
export class NameMapComponent {
private components = new Map<string, Component>();
constructor(components: Component[]) {
for (let i = 0; i < components.length; i++) {
const component = components[i];
this.components.set(component.name, component);
}
}
getComponent(name: string): Component | undefined {
return this.components.get(name);
}
setComponent(component: Component):void {
const name = component.name;
this.components.set(name, component);
}
getAllComponent(): { [key: string]: Component }[] {
const components: { [key: string]: Component }[] = [];
for (const [key, value] of this.components) {
components.push({[key]: value});
}
return components;
}
}
export class RegisterNMC {
private static nmc = new Map<string, NameMapComponent>();
static setNmc(name: string, value: NameMapComponent) {
this.nmc.set(name, value);
}
static getNmc(name: string): NameMapComponent | undefined {
return this.nmc.get(name);
}
}
type Component = new (...args: any[]) => any;
在ngMgdule文件中,必须将要动态加载的组件放入entryCompoent。
const registerComponents = [WillBeCreateComponent]; const nmc =新的NameMapComponent(registerComponents); RegisterNMC.setNmc('component-demo',nmc);
3。在容器组件中
@ViewChild('insert', {read: ViewContainerRef, static: true}) insert: ViewContainerRef;
nmc: NameMapComponent;
remoteData = [
{name: 'WillBeCreateComponent', options: '', pos: ''},
];
constructor(
private resolve: ComponentFactoryResolver,
) {
this.nmc = RegisterNMC.getNmc('component-demo');
}
ngOnInit() {
of(this.remoteData).subscribe(data => {
data.forEach(d => {
const component = this.nmc.getComponent(d.name);
const componentFactory = this.resolve.resolveComponentFactory(component);
this.insert.createComponent(componentFactory);
});
});
}
很好,希望能为您提供帮助^ _ ^!
答案 5 :(得分:0)
我到处寻找能够满足Angular 9对动态加载模块的要求的解决方案,我想到了这一点
import {
ComponentFactory,
Injectable,
Injector,
ɵcreateInjector as createInjector,
ComponentFactoryResolver,
Type
} from '@angular/core';
export class DynamicLoadedModule {
public exportedComponents: Type<any>[];
constructor(
private resolver: ComponentFactoryResolver
) {
}
public createComponentFactory(componentName: string): ComponentFactory<any> {
const component = (this.exportedComponents || [])
.find((componentRef) => componentRef.name === componentName);
return this.resolver.resolveComponentFactory(component);
}
}
@NgModule({
declarations: [LazyComponent],
imports: [CommonModule]
})
export class LazyModule extends DynamicLoadedModule {
constructor(
resolver: ComponentFactoryResolver
) {
super(resolver);
}
}
@Injectable({ providedIn: 'root' })
export class LazyLoadUtilsService {
constructor(
private injector: Injector
) {
}
public getComponentFactory<T>(component: string, module: any): ComponentFactory<any> {
const injector = createInjector(module, this.injector);
const sourceModule: DynamicLoadedModule = injector.get(module);
if (!sourceModule?.createComponentFactory) {
throw new Error('createFactory not defined in module');
}
return sourceModule.createComponentFactory(component);
}
}
用法
async getComponentFactory(): Promise<ComponentFactory<any>> {
const modules = await import('./relative/path/lazy.module');
const nameOfModuleClass = 'LazyModule';
const nameOfComponentClass = 'LazyComponent';
return this.lazyLoadUtils.getComponentFactory(
nameOfComponentClass ,
modules[nameOfModuleClass]
);
}