Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use @Output with <router-outlet> of "angular 4.0"

Tags:

Use a selector to succeed.

<app-child1 (onVoted)="onVoted($event)"></app-child1>

But using a router will fail

<router-outlet  (onVoted)="onVoted($event)"></router-outlet>

I want to receive a value from a component displayed on the "router-outlet".

Please tell me what method I have.

app:https://toparent.herokuapp.com/ src:https://github.com/kuniatsu/routerQuestion

<h1>
  {{title}}
</h1>
<a href="c1">child1</a>
<router-outlet  (onVoted)="onVoted($event)"></router-outlet><!--fail-->
<hr />
<app-child1 (onVoted)="onVoted($event)"></app-child1><!--success-->
like image 778
くにあつ Avatar asked May 05 '17 04:05

くにあつ


1 Answers

You can define an @Output event emitter in the component being rendered at router-outlet. define router outlet as follows.

*.html
<router-outlet (activate)="onActivate($event)"></router-outlet>

In your component you can do as so.

onActivate(elementRef) {
    elementRef.<the @Output eventEmitter>.subscribe(event => {
        console.log(event);
    });
}

This way you can send the events to the component which is rendering router-outlet. This works because @Output event emitters are event streams and you can subscribe to those events.

https://angular.io/api/router/RouterOutlet

like image 177
mruanova Avatar answered Sep 21 '22 10:09

mruanova