Communicate between components Angular 2

How do Components Communicate with Each Other in Angular 2?

In Angular 1, I have some ways to communicate between controllers i.e.
1.      $rootScope,
2.      $scope,
3.      $emit,
4.      $broadcast

Now In Angular 2, we have different ways to communicate between components.

A parent component and its children share a service whose interface enables bi-directional communication within the family.


The following examples for Services communication,
import {Injectable} from '@angular/core';

@Injectable()
export class MyService {
  constructor() { }
}

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

@Component({
  selector: 'my-app',
  templateUrl: './myApp.component.html'
})
export class MyAppComponent { }

The following example to calling service from any other component,
import {Component, OnInit} from '@angular/core';
import {MyService} from './app/myService'; 

@Component({
  selector: '<my-component></my-component>',
  templateUrl: 'app/component.html',
  providers: [MyService]
})

export class MyComponent implements OnInit {
  constructor(private msInstance: MyService) {}
  ngOnInit() { 
      this.msInstance.getServices(); 
  }
}

Example for Sibling Component Communication,

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ListComponent } from './list.component';
import { DetailComponent } from './detail.component';

@Component({
  selector: 'app-component',
  template: '<list-component></list-component><detail-component></detail-component>',
  directives: [ListComponent, DetailComponent]
})
class AppComponent implements AfterViewInit {
  @ViewChild(ListComponent) listComponent:ListComponent;
  @ViewChild(DetailComponent) detailComponent: DetailComponent;

  ngAfterViewInit() {
    // afther this point the children are set, so you can use them
    this.detailComponent.doSomething();
  }
}



I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.