Please refer the plunker, in that you can notice the child component "Loader" is loaded multiple times whenever the button is clicked i.e. on every click a new instance is being created.
How do I avoid creating multiple instance of the same component? My requirement whenever the button is clicked the new instance should replace the existing? how to do this?
Parent component
import { Component, ViewChild, ViewContainerRef, ComponentResolver, Injector, AfterViewInit } from '@angular/core';
import {Loader} from './Loader';
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Hello {{name}}</h2>
<input type="button" (click)="onclick($event)" value="Click"/>
<h3>Loading component</h3>
<load></load>
</div>
`,
directives: [Loader]
})
export class App {
constructor(private _injector: Injector, private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {
this.name = 'Angular2 (Release Candidate!)';
console.log("in constructor of App");
}
@ViewChild(Loader, { read: ViewContainerRef }) childContainer;
onclick(event)
{
this._cr.resolveComponent(Loader).then(cmpFactory => {
console.log("Creating component");
this.childContainer.createComponent(cmpFactory,null, this._injector);
let cmpRef = this.childContainer.createComponent(cmpFactory);
cmpRef.instance.ParentID = "55";
});
}
}