问题
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>
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"
回答1:
Binding with dynamically added components is not supported.
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);
}
回答2:
This is a workaround.
from the code posted above.
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);
}
Make dynamic variable as a Object and now assign it to the variable in parent component.
//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;
Now bindedValue and selectedValue will have the same object reference. Both will hold the same value.
来源:https://stackoverflow.com/questions/39951686/angular-2-dynamic-two-way-binding