2

我正在尝试将 a [formControl](和其他顶级属性)附加到我使用 a 创建的对象,ComponentFactoryResolver以便使用 a 处理表单逻辑ControlValueAccessor

基本上我这样做:

@Component({selector: 'my-selector', ... })
class ATypeWhichSupportsValueAccessor implements ControlValueAccessor {
    @Input()
    otherValuableAttribute: boolean = false;

    // Implementation of ControlValueAccessor
    // ...
    //
}

@Component({selector: 'my-dynamic', template: '<ng-template #container></ng-template>', ... })
class CreateDynamic {
    constructor(
        private vcRef: ViewContainerRef,
        private resolver: ComponentFactoryResolver
    ) {}

    @ViewChild('container', { read: ViewContainerRef })
    container: ViewContainerRef;

    // ...

    create() {
        let type = ATypeWhichSupportsValueAccessor;
        let factory = this.resolver.resolveComponentFactory(type);
        let injector = Injector.create([], this.vcRef.parentInjector);

        // How to attach top level attributes to my control here?
        this._factoryComponent = this.container.createComponent(factory, 0, injector);
    }
}

我想出这一点的唯一方法是进入 JIT 并使用 RuntimeCompiler,动态创建一个模板,如<my-component [formControl]="args" [otherValuableAttribute]="true"></my-component>. 编译它,然后获取实例。

但是,如果不关闭 AOT,我将无法运行它。

我在这里最好的选择是什么?

4

0 回答 0