Angular 2动态双向绑定 [英] 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>
通过添加一个元素可以很好地工作,但是我不知道如何动态绑定双向,就像我在静态组件中一样:[(ngModel)]="selectedValue"
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"
推荐答案
不支持与动态添加的组件绑定.
Binding with dynamically added components is not supported.
您可以使用共享服务与动态添加的组件进行通信( https ://angular.io/docs/ts/latest/cookbook/component-communication.html )
或者您可以使用this.currentComponent
参考文献来强制性地阅读/设置:
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);
}
这篇关于Angular 2动态双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!