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 c
The issue here is that dynamically loaded components don't have a parent / child relationship with the components where they're loaded in. That's why to access properties from the dynamically loaded component you have to use ref.instance.property. The component is not being compiled along with the parent, therefore the parent knows nothing about the foster component.
Now, that being said, what you can do is to make a property that you can subscribe to and I wouldn't use an EventEmitter for that.
My solution would be to use a Subject instead (as I'm doing in a little project of my own).
Your dynamic component would look like this
class DynamicCmp {
// Subject instead of an EventEmitter
lowerIndex: Subject<boolean> = new Subject();
remove() {
// We send true, although in the example is not being used
this.lowerIndex.next(true);
// Remove the component from the view
this._ref.dispose();
}
}
Your component where you're loading the dynamic component
template : '<div #location></div>'; // Note that I removed (lowerIndex)="..."
this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => {
//...
// Subscribe to the Subject property
ref.instance.lowerIndex.subscribe(v => {
this.idx--;
console.log("subtracted");
});
});
Here's your plnkr working and updated to beta.12.