2

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?

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
jsgoupil
  • 3,788
  • 3
  • 38
  • 53
  • Have you tried `this._factoryComponent.instance.formControl = ...`? – yurzui Jun 16 '18 at 05:37
  • @yurzui You can't do that... there is plenty of Angular logic attached to the [formControl] that need to execute when the component is loaded in a template. – jsgoupil Jun 16 '18 at 17:03
  • I thought your directive takes formControl input. There is no simple way to do this. Check similar question https://stackoverflow.com/questions/44181152/how-to-dynamically-add-ng-value-accessor-component-to-reactive-form – yurzui Jun 16 '18 at 17:42
  • @yurzui yeah that's not the best solution, having to learn how the internal of formControl works. – jsgoupil Jun 17 '18 at 18:48

0 Answers0