Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emitting event from root component to router outlet child component

Tags:

angular

I have the following structure: app.component.html holds the following components:

<componentA>
<router-outlet></router-outlet>

I inject componentB into the router outlet and componentB has its own router outlet.

<componentB><router-outlet></router-outlet></componentB>

I inject componentC inside ComponentB´s router outlet

<componentC>

I want to send an event from ComponentA to ComponentC.

I am trying to use a service to accomplish this by injecting it into ComponentA which sends the event and ComponentC is subscribing to the event through the injected service. Component C is not receiving the events.

However if I move componentA inside ComponentB the event is successfully emitted to ComponentC.

How can I emit the event from ComponentA to ComponentC when ComponentA is located at the root in app.component.html?

[UPDATE]

I followed the example on bidirectional service but the event is still not received. Here is the code:

My Service:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class MyService {
   private mySource = new Subject<string>();
   source$ = this.mySource.asObservable();
   sendEvent(stringParam: string) {
      this.mySource.next(stringParam);
   }
}

Component A sends the event

 this.myService.sendEvent("test");

Component C subscribes and listens for the event

this.subscription = this.myService.source$.subscribe(stringParam => {
  console.log('Received event: ' + stringParam);
});

I am using Angular RC5. Any idea what I am missing?

like image 827
doorman Avatar asked Aug 24 '16 21:08

doorman


People also ask

How do you emit an event from parent to child?

Just change the value of an expression passed as Input to the child component, and the child component will get it (and be informed by ngOnChanges). You could also emit an event using a shared service that has an Observable.

What is Children in routing in angular?

With child routes, you can have a component-like structure defined for the routes in your app. It is critical as there are views that the user should not be able to access unless they are in a particular view. This way, the structure becomes tree-like, just like the structure of components.


1 Answers

At first, the router doesn't add components into the <router-outlet> but makes it a sibling. This is because of how ViewContainerRef.createComponent works.

Events sent from EventEmitter also don't bubble and therefore can only be used to add event handlers on child elements using (event)="doSomething()".

A shared service is usually the right thing to use in your situation. For more details see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

like image 143
Günter Zöchbauer Avatar answered Sep 20 '22 21:09

Günter Zöchbauer