How can I use an event emitter on a dynamically added component?

后端 未结 1 650
长情又很酷
长情又很酷 2020-12-30 03:17

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

相关标签:
1条回答
  • 2020-12-30 04:06

    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.

    0 讨论(0)
提交回复
热议问题