Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Passing data to component when dynamically adding the component

Tags:

angular

I have dynamically added a component on the click of a button .

Below is the code for my widget . Simple div with color property being set as input.

Widget.tmpl.html

 div class="{{color}}" (click)="ChangeColor()"

In the Widget component i am taking color as my input . This component works fine when i add it manually . But now i am trying to dynamically add the component and also need to pass the Color Value to the Widget Component.

Below is the code in the app.component.ts where i am calling addItem() on the button click .

app.component.ts

export class AppComponent  {
  @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;
  private componentFactory: ComponentFactory<any>;

  constructor(componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler) {
    this.componentFactory = componentFactoryResolver.resolveComponentFactory(MyAppComponent);

  }

  addItem () {
   this.viewContainerRef.createComponent(this.componentFactory, 0);
  }

 public  myValue:string = 'red';

 onChange(val: any) { this.myValue = val; } }

In the addItem() method i am dynamically adding my widget component to my view. The component gets added fine . But the problem is how to pass the color property when dynamically adding . Based on what color i pass when creating the widget i want it to be displayed in red or green etc. How to property bind in this scenario?

Here is some of the Code :

export class MyAppComponent { 

    @Input() color; 
    @Output('changes') result: EventEmitter<any> = new EventEmitter(); 

    public constructor() { 
    }

    ChangeColor() {
        this.ToggleColor();
        this.result.emit(this.color);// Emitting the color to the parent.        
    }

    ToggleColor() {
        if (this.color == "red")
            this.color = "blue";
        else
            this.color = "red";
    }
}

In the above code i am emitting my color to the parent app.component.ts but since i have dynamically added the widget component , i dont know where to add this code (changes)="onChange($event)". I tried to add this code in the div as shown below :

<div class="{{color}}" (click)="ChangeColor()" (changes)="onChange($event)"></div>

But it does not work.

like image 412
maxrow Avatar asked Aug 31 '16 07:08

maxrow


1 Answers

var cmpRef = this.viewContainerRef.createComponent(this.componentFactory, 0);
cmpRef.instance.someProp = 'someValue';
cmpRef.instance.someObservable.subscribe(val => this.someProp = val);
like image 178
Günter Zöchbauer Avatar answered Oct 19 '22 23:10

Günter Zöchbauer