7ball
7ball

Reputation: 2315

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

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?

Upvotes: 1

Views: 1549

Answers (1)

micronyks
micronyks

Reputation: 55443

I hope this is what you want.

LIVE DEMO : http://plnkr.co/edit/SPbo1Cw7mDadfLK3ElEC?p=preview

src/dynamic-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

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.

Upvotes: 2

Related Questions