Ser*_*eyK 5 angular-ngmodel angular
我正在尝试构建一个动态附加另一个组件的组件.这里的例子是我的父类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
sample-component.component.html:
<div #dynamicContent></div>
Run Code Online (Sandbox Code Playgroud)
它可以附加一个元素,但我不知道如何动态绑定双向,就像我在静态组件中一样: [(ngModel)]="selectedValue"
不支持使用动态添加的组件绑定.
您可以使用共享服务与动态添加的组件进行通信(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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2430 次 |
| 最近记录: |