我正在尝试构建一个动态附加另一个组件的组件。作为一个例子,这是我的父类:
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"
不支持与动态添加的组件绑定。
您可以使用共享服务与动态添加的组件进行通信(https://angular.io/docs/ts/latest/cookbook/component-communication.html 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)