How to attach a [formControl] to an type when instantiating it in Angular

430 views Asked by At

I am trying to attach a [formControl] (and other top level attributes) to an object that I create with a ComponentFactoryResolver in order to handle the form logic with a ControlValueAccessor.

Basically I do this:

@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);
    }
}

The only way I figured this out is by going in JIT and using a RuntimeCompiler, creating a template on the fly like <my-component [formControl]="args" [otherValuableAttribute]="true"></my-component>. Compiling this, then getting the instance.

However, I can't run this without turning off AOT.

What is my best option here?

0

There are 0 answers