Search code examples
angularangular2-routingeventemitter

Angular 2 emit event to application root component


I want to emit an event to the component that is the bootstrap of my application. This component is the handler of a websocket connection, I need to send a message and this is why I have to emit this event.

In the bootstrap component I have only <router-outlet></router-outlet> so I cannot realize how I can receive the event.

Example

App.component.html

<router-outlet></router-outlet>

App.component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})

export class AppComponent {
}

App.module.ts

...
@NgModule({
  ...
  bootstrap: [AppComponent]
})

App-routing.module.ts

...
const routes: Routes = [
  { path: 'display', component: MapDisplayComponent }
];

Map-display.components.ts

@Component({
  selector: 'app-map-display',
  templateUrl: './map-display.component.html',
  styleUrls: ['./map-display.component.scss']
})
export class MapDisplayComponent {
    @Output() sendMessage: EventEmitter<any> = new EventEmitter<any>();
}

So the problem is that the map-display component has to send the event to his parent


Solution

  • Use a service.

    1. Inject service into component and main component.
    2. Add an emitter or an Observable to the service.
    3. Add a function in the service to change the value of the Observable / emit a new value if your using an emitter.
    4. Use the function in your component.
    5. Subscribe to the emitter or the Observable in your main Component.

    Hope this helps.