Angular 2动态双向绑定

谢尔盖·K

我正在尝试构建一个可以动态附加另一个组件的组件。作为示例,这是我的父类:

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"

贡特·佐赫鲍尔(GünterZöchbauer)

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

您可以使用共享服务与动态添加的组件(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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章