1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Following this approach, is there a way to use inheritance on the dynamically created components? For example, I'd like to have some sort of base template where the dynamically created components' templates can inherit from. Is this possible?
The plunker doesn't seem to work for me. So I made a StackBlitz version: angular-bo1yaw.stackblitz.io

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.