简体   繁体   English

数据绑定Angular2动态创建的组件

[英]Data binding Angular2 dynamically created components

I've found code to dynamically create child components, pass data to them, and render them accordingly. 我发现了可以动态创建子组件,将数据传递给它们并相应地渲染它们的代码。

http://plnkr.co/edit/wwHEZkbvKmNVF0Snr2ZB?p=preview http://plnkr.co/edit/wwHEZkbvKmNVF0Snr2ZB?p=preview

However, I'm not sure how to bind the data from the child components to its parent. 但是,我不确定如何将数据从子组件绑定到其父组件。 In the Plunker I included above, I'd like to have 2-way data binding to showNum .. Any idea? 在上面包含的Plunker中,我想将2路数据绑定到showNum ..知道吗?

I hope this is what you want. 我希望这就是你想要的。

LIVE DEMO : http://plnkr.co/edit/SPbo1Cw7mDadfLK3ElEC?p=preview 实时演示: http : //plnkr.co/edit/SPbo1Cw7mDadfLK3ElEC?p=preview

src/dynamic-component.ts 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-world-component.ts 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
    }

  }

})

Parent

<div *ngFor="let x of components">showNum of parent: {{x.inputs.showNum}}<br></div>

same with world-hello-component.ts . world-hello-component.ts相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM