javascript - Angular 2 : ngOnChange not firing on deletion of component -
i have close button on each element , if close , component getting deleted , why not able add same component again ?example : if close component boxone , try add again it's not working. here working demo
parent-container.ts
import { ngmodule, component, compiler, viewcontainerref, viewchild, input, componentref, componentfactory, componentfactoryresolver, changedetectorref,onchanges } '@angular/core' import { subject } 'rxjs'; import { sharedservice } './shared.service'; @component({ selector: 'parent-container', template: ` <ng-template id="target" #target></ng-template> `, styles: [] }) export class parentcontainer implements onchanges { @viewchild('target', { read: viewcontainerref }) target; @input() type; cmpref: componentref<any>; private isviewinitialized: boolean = false; constructor(private componentfactoryresolver: componentfactoryresolver, private compiler: compiler, private cdref: changedetectorref, private sharedserv: sharedservice) { } updatecomponent() { if (!this.isviewinitialized) { return; } if (this.cmpref) { this.cmpref.destroy(); } let factory = this.componentfactoryresolver.resolvecomponentfactory(this.type); this.cmpref = this.target.createcomponent(factory); this.cmpref.instance.close$.take(1).subscribe(() => this.cmpref.destroy()); this.cdref.detectchanges(); } ngonchanges() { this.updatecomponent(); } ngafterviewinit() { this.isviewinitialized = true; this.updatecomponent(); } ngondestroy() { if (this.cmpref) { this.cmpref.destroy(); } } }
boxone.component.ts
import { component, input ,ondestroy } '@angular/core'; import { subject } 'rxjs'; import { sharedservice } './shared.service'; @component({ selector: 'box-one', template: ` <div> <button (click)="close({'name':'boxonecomponent','length':2})">close</button> </div> `, styles: [` div{ height:100px; width:100px; background-color:yellow; display:inline-block; margin:5px; } button{ margin-left:48px; } `] }) export class boxonecomponent implements ondestroy { constructor(private sharedserv : sharedservice){} public close$ = new subject<void>(); public boxlength$ = new subject<number>(); close(comps){ this.sharedserv.sendcomponentname(comps); this.close$.next(null); this.boxlength$.next(2); } ngondestroy(){ } }
if delete component clicking close , ngonchange not detecting changes , updatecomponent function not getting triggered . there other alternative . please .
Comments
Post a Comment