Angular 2动态双向绑定

时间:2016-10-10 05:20:02

标签: angular angular-ngmodel

我正在尝试构建一个动态附加另一个组件的组件。这里的例子是我的父类:

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>

它可以附加一个元素,但我不知道如何动态绑定双向,就像我在静态组件中一样:[(ngModel)]="selectedValue"

2 个答案:

答案 0 :(得分:8)

不支持使用动态添加的组件进行绑定。

您可以使用共享服务与动态添加的组件(https://angular.io/docs/ts/latest/cookbook/component-communication.html)进行通信 或者您可以使用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);
}

答案 1 :(得分:0)

这是一种解决方法。

来自上面发布的代码。

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将具有相同的对象引用。两者将具有相同的值。