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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With