Есть способ создать некий компонент Angular 2+ "Фабрика" и разрешить его с помощью ComponentFactoryResolver? - PullRequest
0 голосов
/ 22 апреля 2020

Я хочу создать тип "фабрики" из 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

Итак, мой вопрос: это плохая практика? Есть еще один способ сделать что-то подобное?

...