[英]Angular2 data binding for Dynamically created mutl select html element
[英]Data binding Angular2 dynamically created components
我發現了可以動態創建子組件,將數據傳遞給它們並相應地渲染它們的代碼。
http://plnkr.co/edit/wwHEZkbvKmNVF0Snr2ZB?p=preview
但是,我不確定如何將數據從子組件綁定到其父組件。 在上面包含的Plunker中,我想將2路數據綁定到showNum
..知道嗎?
我希望這就是你想要的。
實時演示: http : //plnkr.co/edit/SPbo1Cw7mDadfLK3ElEC?p=preview
SRC /動態component.ts
import 'rxjs/Rx';
export default class DynamicComponent {
myData:any;
@Input() set componentData(data: {component: any, inputs: any }) {
...
this.myData=data; //assinging parent data object to myData object.
...
...
component.instance.showNum=this.myData.inputs.showNum
//component.instance.someNumber syntax allows you to pass varible to dynamically created component
//here, I'm using subject from rxjs and subscribing to it as below
component.instance.emitNumber$.subscribe(v=>{
console.log('getting'+ v);
console.log(this.myData);
this.myData.inputs.showNum=v; //assigning subscribed value back to parent object
console.log(this.myData);
});
}
SRC /你好,世界component.ts
import {Observable,Subject} 'rxjs/Rx';
@Component({
selector: 'hello-world',
template: `
...
<input [(ngModel)]="showNum" (keyup)="updateValue(showNum)" type="text">
`,
export default class HelloWorldComponent {
@Input() showNum:number;
emitNumber=new Subject<number>(); //using rxjs subject
emitNumber$=this.emitNumber.asObservable();
updateValue(val){
this.emitNumber.next(val); //emitting value back to dyanmic component
}
}
})
親
<div *ngFor="let x of components">showNum of parent: {{x.inputs.showNum}}<br></div>
與world-hello-component.ts相同 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.