Angular: parent/child and sibling component communication

Here we will learn how to pass data between components. Does not matter if the component is a parent or a child. This is a global solution to pass data to a component or trigger an event in another component.

In this example we can see that we have a CommonService class which is used in both components that we are going to use: Component0 and Component1. Component0 emits events, and Component1 subscribes to the event emitter and catches the event when it is emitted.

common.service.ts

import {EventEmitter, Injectable, Output} from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  @Output()
  public commonServiceEmitter: EventEmitter<any> = new EventEmitter();

  constructor() {}
}

component0.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component0',
  templateUrl: './component0.component.html',
  styleUrls: ['./component0.component.css']
})
export class Component0Component implements OnInit {

  constructor(private commonService: CommonService) { }

  ngOnInit(): void {}

  myEmitter(): void{
      this.commonService.commonServiceEmitter.emit({data: 'update'});
  }

}

component1.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {

  constructor(private commonService: CommonService) { 
    this.commonService.commonServiceEmitter.subscribe((data: any) => {this.myMethod();});
  }

  ngOnInit(): void {}

   myMethod(): void {
       console.log('Hello World!');
   }

}