I have created dynamic component manually using button click. If we click on Add button it will create component next to the add button. If we click on Remove button it will remove the component.
Here, the problem is while creating the component using ngFor, unable to remove component while clicking on Remove button. I noticed Remove function call is not happening while creating the component using ngFor.
Below my code:
Parent Component:
import{ Component, Input, Output, EventEmitter, ViewContainerRef, ElementRef, ComponentRef, ComponentResolver, ViewChild, ComponentFactory } from '@angular/core';
import {ChildCmpt } from './child-cmpt';
import {SharedData } from './SharedData';
@Component({
selector: 'my-app',
templateUrl: 'src/parent-cmpt.html',
directives: [ChildCmpt]
})
export class ParentCmpt {
myAllNames: any;
@Input() thing:string;
//allItems: ItemsAddRemove;
constructor(private resolver: ComponentResolver, private appItems: SharedData) {
this.myAllNames = this.appItems.getNames();
}
idx:number = 0;
@ViewChild('location', { read: ViewContainerRef}) location: ViewContainerRef;
add() {
this.resolver.resolveComponent(ChildCmpt).then((factory:ComponentFactory<any>) => {
let ref = this.location.createComponent(factory)
ref.instance._ref = ref;
ref.instance._idx = this.idx++;
ref.instance._thing = this.thing;
//allItems.push(ref);
this.appItems.addMyItem(ref);
});
}
submit(a: any) {
let temp = this.appItems.getMyItem();
let componentThings = temp.map((compRef) => compRef.instance.thing);
alert(componentThings);
}
removeAll = ():void => {
// do cleanup stuff..
this.location.clear();
this.appItems.removeAll();
}
}
Child Component:
import { Component, Input, Output, EventEmitter, ViewContainerRef, ElementRef, ComponentRef, ComponentResolver, ViewChild, ComponentFactory } from '@angular/core';
import {SharedData } from './SharedData';
@Component({
selector: 'child-cmpt',
templateUrl: 'src/child-cmpt.html'
})
export class ChildCmpt {
_ref:ComponentRef<any>;
_idx:number;
allVal = [];
@Input() thing:string;
public components = [];
constructor(private resolver: ComponentResolver, private location: ViewContainerRef, private appItems: SharedData) {
}
remove() {
let temp = this.appItems.getMyItem();
delete temp[temp.indexOf(this._ref)];
this._ref.destroy();
}
add() {
this.resolver.resolveComponent(ChildCmpt).then((factory:ComponentFactory<any>) => {
let ref = this.location.createComponent(factory, 0);
ref.instance._ref = ref;
ref.instance._idx = this._idx++;
ref.instance._thing = this.thing;
//this.allItems.push(ref);
this.appItems.addMyItem(ref);
});
}
}
Please help me to fix this issue. Much appreciate your help.
Thanks in Advance.