Andrea Caruso Andrea Caruso - 4 months ago 28
AngularJS Question

Angular 2: Event not firing

I'm trying to fire an event when my component gets the logged user from a service because I would like to show the navigation bar only when a user is logged in.

Here's my app.component code:

import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { LoginComponent } from './login.component';
import { DashboardComponent } from './dashboard.component';
import { ControlDetailComponent } from './control-detail.component';
import { PageNotFoundComponent } from './pagenotfound.component';
import { SettingsComponent } from './settings.component';
import { UserService } from '../service/user.service';
import { User } from '../object/user';

@Component({
selector: 'myApp',
templateUrl: './app/template/app.component.html',
styleUrls: ['styles.css'],
directives: [ROUTER_DIRECTIVES],
precompile: [LoginComponent, DashboardComponent, ControlDetailComponent, PageNotFoundComponent, SettingsComponent]
})
export class AppComponent {
@Input() loggedUser:User;
@Output() userChanged:EventEmitter<User> = new EventEmitter<User>();

constructor(private _userService:UserService, private _router:Router) {}

ngAfterViewInit() {
if(this._userService.isUserLogged()) {
this.userChanged.emit(this._userService.loggedUser);
}
}

switchUser(event) {
this.loggedUser = event.target.value;
console.log("event triggered");
}
}




And this is its associated template:

<div class="all-content">
<nav (userChanged)="switchUser($event)" *ngIf="loggedUser">
<ul>
<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
<a [routerLink]="['/settings']" routerLinkActive="active">Settings</a>
<a (click)="logout()">Logout</a>
</ul>
</nav>







Someone knows why my event is not fired?

Initially I thought the problem was the
*ngIf
directive that was preventing the firing of the event but, even removing that, the event is not fired anyway...

Answer

Events emitted by @Output()s can only be subscribed to on the parent component or a directive applied on the element. The AppComponent doesn't have a parent component, therefore this approach won't work.

In your case it's better to use a shared service with observables. https://angular.io/docs/ts/latest/cookbook/component-communication.html