Search code examples
angularangular-ngmodel

Angular 2 dynamic two-way binding


I'm trying to build a component that appends another component dynamically. As an example here is my parent class:

import { Component, ComponentRef, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';

@Component({
    templateUrl: './app/sample-component.component.html',
    selector: 'sample-component'
})
export class SampleComponent {

    @ViewChild('dynamicContent', { read: ViewContainerRef })
    protected dynamicComponentTarget: ViewContainerRef;
    private currentComponent: ComponentRef<any>;
    private selectedValue: any;

    constructor(private componentResolver: ComponentFactoryResolver) {

    }

    private appendComponent(componentType: any) {
        var factory = this.componentResolver.resolveComponentFactory(componentType);
        this.currentComponent = this.dynamicComponentTarget.createComponent(factory);
    }
}

sample-component.component.html:

<div #dynamicContent></div>

It works fine with appending an element, but i have no idea about how to bind two-way dynamically, like i do in static components: [(ngModel)]="selectedValue"


Solution

  • Binding with dynamically added components is not supported.

    You can use a shared service to communicate with dynamically added components (https://angular.io/docs/ts/latest/cookbook/component-communication.html)
    or you can read/set imperatively using the this.currentComponent reference:

    private appendComponent(componentType: any) {
        var factory = this.componentResolver.resolveComponentFactory(componentType);
        this.currentComponent = this.dynamicComponentTarget.createComponent(factory);
        this.currentComponent.instance.value = this.selectedValue;
        this.currentComponent.instance.valueChange.subscribe(val => this.selectedValue = val);
    }