Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Pass values to a dynamic component created with ComponentFactory

I was following Günter Zöchbauer's advice on how to create dynamic components and I was wondering how I could pass values to it - as in, the child component has an @input.

Using the plunker example given in the above question - plunker - how could I pass the child component a string, lets call it message, that would then display when clicking the 'add' button.

Here's an example of how the child component might look:

import {Component OnChanges, Input} from '@angular/core'

    @Component({
      selector: 'hello',
      providers: [],
      template: `<h1>{{message}}</h1>`,
      directives: []
    })
    export class HelloComponent implements OnChanges {
      @Input() message:any;

      constructor() {
      }

      ngOnChanges(changes:any){
      }
    }
like image 748
Jack Rothrock Avatar asked Aug 19 '16 23:08

Jack Rothrock


1 Answers

You can try below,

  let instance  = this.viewContainerRef.createComponent(this.componentFactory, 0).instance;
  instance.message = "some text!!";

Here is the Plunker!!

like image 103
Madhu Ranjan Avatar answered Nov 02 '22 12:11

Madhu Ranjan