How to communicate between component in Angular? How to communicate between component in Angular? angular angular

How to communicate between component in Angular?


If you are trying to communicate from a parent component to a child component, this is pretty clearly described using @Input and EventEmitters with @Output in the angular docs.

Angular 2 component interaction

As for communication across siblings, I posted an answer in a similar question that might help with the issue of sharing data across sibling components. Currently, i think the shared service method is the most efficient.

angular-2-sibling-component-communication


Using a service:

import { Injectable } from '@angular/core';import { Subject }    from 'rxjs/Subject';@Injectable()export class AppState {  public _subject = new Subject<object>();  public event = this._subject.asObservable();  public publish(data: any) {    this._subject.next(data);  }}

and you can publish event-like messages like this:

export class AppComponent {  constructor(    public appState: AppState  ) {    appState.publish({data: 'some data'});  }}

and you can subscribe to these events:

export class HomeComponent {  constructor(    public appState: AppState  ) {    appState.event.subscribe((data) => {      console.log(data); // {data: 'some data'}    });  }}


  1. @Input and @Output

    If there are multipart componentsyou can use @Input and @Output to exchange data.Document : https://angular.io/guide/component-interaction

    example: https://angular.io/generated/live-examples/component-interaction/eplnkr.html

  2. Dependency Injection

    you can store the data in Service, and then inject Service into the component which you want. such as "user.server.ts" in the example:

    https://angular.io/generated/live-examples/dependency-injection/eplnkr.html