首页 > 解决方案 > 有一种方法可以创建一种 Angular 2+ 组件“工厂”并使用 ComponentFactoryResolver 解决它?

问题描述

我想创建一种 Angular 组件的“工厂”类型并使用ComponentFactoryResolver解决它。我的意思是,我有一个组件,例如:

@Component({
    selector: "my-component",
    templateUrl: "./component.html",
    styleUrls: ["./component.scss"]
})
export class BaseComponent {

    property: string;

    constructor(private myService: MyService) {}

    // more stuff
}

我试图做类似的事情:

export class SomeKindOfWeirdFactory {
    static withProperty(property: string): new <T extends BaseComponent>() => any {
        class BaseComponetWithProperty extends BaseComponent {
            property: string = property;
        }
        return BaseComponetWithProperty as any;
    }
}

并像这样使用它:

SomeKindOfWeirdFactory.withProperty("one property"); // BaseComponetWithProperty, but with "one property" as property.
SomeKindOfWeirdFactory.withProperty("other property"); // BaseComponetWithProperty, but with "other property" as property.

所以,我的问题是当我尝试使用 Angular Component Factory Resolver 解析组件时。

// other file.ts
const component = componentFactoryResolver.resolveComponentFactory(SomeKindOfWeirdFactory.withProperty("the correct property"));
// ERROR Error: "No component factory found for BaseComponetWithProperty. Did you add it to @NgModule.entryComponents?"

因此,我尝试导出 BaseComponentWithProperty 类并将其导入到 NgModule 和 entryComponents,但无论如何它都不起作用。

// without this annotation the NgModule import has an error
@Component({
    templateUrl: "./component.html",
    styleUrls: ["./component.scss"]
})
export class BaseComponetWithProperty extends BaseComponent {
    property: string;
}

export class SomeKindOfWeirdFactory {
    static withProperty(property: string): new <T extends BaseComponent>() => any {
        class BaseComponetWithProperty extends BaseComponent {
            property: string = property;
        }

        return BaseComponetWithProperty as any;
    }
}

...
// other file.ts
const component = componentFactoryResolver.resolveComponentFactory(SomeKindOfWeirdFactory.withProperty("the correct property"));
// Still no resolve the component

所以,我的问题是:这是一种不好的做法吗?还有另一种方法可以做这样的事情吗?

标签: angulartypescriptclassinheritancefactory

解决方案


推荐阅读