0
我發現代碼來動態創建子組件,將數據傳遞給它們,並相應地呈現它們。數據綁定Angular2動態創建組件
http://plnkr.co/edit/wwHEZkbvKmNVF0Snr2ZB?p=preview
但是,我不知道如何從子組件的數據綁定到其父。在上面包含的Plunker中,我想要將雙向數據綁定到showNum
..任何想法?
我發現代碼來動態創建子組件,將數據傳遞給它們,並相應地呈現它們。數據綁定Angular2動態創建組件
http://plnkr.co/edit/wwHEZkbvKmNVF0Snr2ZB?p=preview
但是,我不知道如何從子組件的數據綁定到其父。在上面包含的Plunker中,我想要將雙向數據綁定到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/HELLO-世界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>
與同世界-HELLO-component.ts。
遵循這種方法,是否有辦法在動態創建的組件上使用繼承?例如,我想要有一些基本模板,動態創建的組件的模板可以從中繼承。這可能嗎? – 7ball