Search code examples
typescriptangulareventemitteremit

How can I emit an event passing the emitter inside a function in Angular 2


Component PARENT (template):

<CHILD></CHILD>
<overlayer *ngIf="showPopup" (evTogglePopup)="onShowPopup($event)"></overlayer>

Component CHILD (@Component):

@Output() evTogglePopup = new EventEmitter();
...
this.inputUt.ajaxCheckExistingEmail(email, this.evTogglePopup);

a funtion of MyInputUtility (a provider @Injectable imported and used into CHILD):

ajaxCheckExistingEmail(email, evEmitter:EventEmitter<any>){
        if (email.valid){
            return this.http.post(
                GLOBAL_CONST.apiPath + "/user/user/api-check-user-email",
                'email=' + email.value,
                {headers: this.headers}
            ).map(response => response.json())
            .subscribe(val => {
                console.log(val);
                if( val.emailExists ){
                    evEmitter.emit(true);
                }
            });
        }
}

This "solution" doesn't work, and I was wondering if it's because evEmitter is passed by copy to the ajaxCheckExistingEmail function.

Sosterd by myself
The problem was that "overlayer" is a different selector form that one pointed by CHILD (selector), and I thought it would have worked as well.

I changed like this below and now it works:

<CHILD (evTogglePopup)="onShowPopup($event)"></CHILD>
    <overlayer *ngIf="showPopup"></overlayer>

Solution

  • Events from @Output() don't bubble. Either you pass it along from one parent to the next or you can use a shared service to share data between elements that are not in a direct parent-child relationship.

    See https://angular.io/docs/ts/latest/cookbook/component-communication.html for details.