Angular 2 EventEmitter

I have a problem where an EventEmitter does not output the value to the parent component. This is how I am set up.

main.component.ts (short version)

... @Component({ selector: 'my-app', templateUrl: '/app/views/main.ejs', directives: [ROUTER_DIRECTIVES], providers:[AuthService], inputs:['userLoggedIn'] }) @RouteConfig([ {path:'/logout', name: 'Logout', component: AuthComponent}, ]) export class AppComponent implements OnInit, CanReuse{ constructor(private _auth_service: AuthService){ this._auth_service.authChanged.subscribe(data=>this.authChangedHandler(data)); } public authChangedHandler($event){ alert($event); } } ... 

auth.component.ts (short version)

 export class AuthComponent implements OnInit, CanReuse{ public loggedIn = false; public user = {}; @Output() authChanged: EventEmitter<string>; public selectedTab = "/login"; constructor(private _router: Router, private _location:Location,private _http: Http, private _auth_service: AuthService){ this.authChanged = new EventEmitter(); this.authChanged.emit("authChanged"); } } 

main.ejs (short version)

 <nav (authChanged)="authChangedHandler($event)"></nav> <router-outlet></router-outlet> 

auth.service.ts

 export class AuthService { public authChanged: EventEmitter<string>; constructor(private _http: Http){ this.authChanged = new EventEmitter(); this.authChanged.emit("authChanged"); } } 

EDIT: I added the AuthService code that I embed in the main component. Now it should work, but it does not work.

+6
source share
2 answers

Events emitted by EventEmitter do not bubble. If an item is added to the router-outlet , then only the router-outlet receives the event, but not the item containing the router-outlet .

You can use the shared service to communicate between the parent and child elements.

For general service see

If you register a shared service in the providers: [] list of the parent component, the service will only be used between the parent and all its descendants. If you add it only to bootstrap(MyApp, [ ..., SharedService]) , then the entire application is shared by one instance.

+14
source

In fact, nav not a parent component of AuthComponent . The latter is involved in routing (see router-outlet ). Therefore, you cannot receive an event for a registered expression in the nav element in HTML.

+1
source

All Articles