Working off of Eric Martinez' answer from Angular 2 - Adding / Removing components on the fly, I want to limit the amount of components created. And then after deleting a component, I'm trying to emit that event to the parent so the parent knows the number of components currently created.
In this Plunker, I limit the number of components by 4, and then I'm trying to emit an event to lower that count back down. The event isn't emitting. How do you emit an event from a dynamically added component?
// dynamic component
@Component({
selector : 'dynamic',
template : `
<div>
Component number {{_idx}} <button (click)="remove()">Remove</button>
</div>`
})
class DynamicCmp {
_ref: ComponentRef;
_idx: number;
@Output lowerIndex = new EventEmitter<any>();
remove() {
this._ref.dispose();
this.lowerIndex.emit(true);
}
}
// Parent container component
@Component({
selector: 'my-app',
template : `
<button (click)="add()">Add new component</button>
<div #location (lowerIndex)="lowerIndex();"></div>
`
})
export class App {
idx: number = 0;
constructor(private _dcl: DynamicComponentLoader, private _e: ElementRef) {}
lowerIndex() {
this.idx--;
console.log("subtracted");
}
add() {
if (this.idx < 4) {
this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => {
ref.instance._ref = ref;
ref.instance._idx = this.idx++;
});
console.log("added")
}
}
}
I posted the components in here because stackoverflow requires code posted with plunker links. Code is exactly the same as seen in plunker