Angular 2 动态 two-way 绑定

Angular 2 dynamic two-way binding

我正在尝试构建一个动态附加另一个组件的组件。例如,这里是我的 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>

它可以很好地附加一个元素,但我不知道如何动态绑定 two-way,就像我在静态组件中所做的那样:[(ngModel)]="selectedValue"

不支持绑定动态添加的组件。

您可以使用共享服务与动态添加的组件通信(https://angular.io/docs/ts/latest/cookbook/component-communication.html)
或者你可以 read/set 使用 this.currentComponent 参考:

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

这是一个解决方法。

来自上面发布的代码。

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

}

将动态变量作为一个对象,现在将其赋值给父组件中的变量。

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

现在 bindedValue 和 selectedValue 将具有相同的对象引用。两者将保持相同的价值。