Angular 6 – Easy way to communicate between two components

This is a quick tutorial to show how you can communicate between components in Angular 6 and TypeScript.

The way to communicate between components is to use an Observable and a Subject (which is a type of observable), I do not want to go too much into the details about how observables work here since it’s a big subject, but in a nutshell there are two methods that we’re interested in: Observable.subscribe() and Subject.next().

Observable.subscribe()
The observable subscribe method is used by angular components to subscribe to messages that are sent to an observable.

Subject.next()
The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers (a.k.a. observers) of that observable.

Here is a simple example showing communication between the home component and the root app component via a message service using observables. Just following the below three steps.

1. Create Message service as below

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MessageService {
private subject = new Subject();

sendMessage(message: string) {
this.subject.next({ text: message });
}

clearMessage() {
this.subject.next();
}

getMessage(): Observable {
return this.subject.asObservable();
}
}

2. Create a component that receive messages.

app.component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { MessageService } from ‘./_services/index’;

@Component({
selector: ‘app’,
templateUrl: ‘app.component.html’
})

export class AppComponent implements OnDestroy {
message: any;
subscription: Subscription;

constructor(private messageService: MessageService) {
// subscribe to home component messages
this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
}

ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}

app.component.html

<div class=”jumbotron”>
<div class=”container text-center”>
<div class=”row”>
<div class=”col-sm-8 offset-sm-2″>
<div *ngIf=”message” class=”alert alert-success”>{{message.text}}</div>
<router-outlet></router-outlet>
</div>
</div>
</div>
</div>

3. Create another Component that Sends Messages

home.component.ts

import { Component } from ‘@angular/core’;

import { MessageService } from ‘../_services/index’;

@Component({ templateUrl: ‘home.component.html’ })
export class HomeComponent {
constructor(private messageService: MessageService) { }

sendMessage(): void {
// send message to subscribers via observable subject
this.messageService.sendMessage(‘Message from Home Component to App Component!’);
}

clearMessage(): void {
// clear message
this.messageService.clearMessage();
}
}

home.component.html

<h2>Angular 6 Component Communication</h2>
<button class="btn btn-primary">Send Message</button>
<button class="btn btn-secondary">Clear Message</button>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.