Check out the plunker link to see that the child component "Loader" is being loaded multiple times every time the button is clicked. How can I prevent creating multiple instances of the same component? I want the new instance to replace the existing one when the button is clicked. Any suggestions on how to achieve this?
Here is the code snippet of the 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";
});
}
}