Andrea Caruso Andrea Caruso - 4 years ago 424
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';

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()) {

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

And this is its associated template:

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

Someone knows why my event is not fired?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download