Angular 2 dynamic two-way binding

戏子无情 提交于 2019-12-07 05:37:22

问题


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"


回答1:


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



回答2:


This is a workaround.

from the code posted above.

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

}

Make dynamic variable as a Object and now assign it to the variable in parent component.

//at dynamically created component
export class DynamicComponent{
public bindedValue : Object = {
 value:''
 }
}

// at dynamic component template
<input type="text" [(ngModel)]="bindedValue.value"/>


//At parent component
this.currentComponent.instance.bindedValue= this.selectedValue;

Now bindedValue and selectedValue will have the same object reference. Both will hold the same value.



来源:https://stackoverflow.com/questions/39951686/angular-2-dynamic-two-way-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!