June 26, 2023 08:27 by
Peter
Information exchange between various application components is essential, and Angular is not an exception. Angular provides a number of built-in methods to facilitate this prevalent practise. Nonetheless, there may be instances in which these default approaches are insufficient, necessitating the implementation of more creative solutions.
In this session, we will investigate a few of the most common methods for component communication.
The resources I used to create this tutorial are listed below.
- Visual Studio Code
- Node 18.14.0
- Angular 15
Input and Output Properties (Parent-Child Communication)'s source code can be downloaded from GitHub.
- You can transfer data between parent and offspring components using input properties.
- Define an input property in the secondary component using @Input(), and then bind the property in the parent component.
- Employ output properties with events to communicate from the child component to the parent component.
- Define an output property in the child component using @Output() and emit events with EventEmitter.
Let's examine the sample code below, which will give you an overview of parent-to-child and child-to-parent communications.
Parent Component
- Input and Output Properties (Parent-Child Communication)
- You can use input properties to pass data from parent to child components.
- Define an input property in the child component using the @Input() decorator, and then bind the property in the parent component.
- Use output properties with events to communicate from the child component back to the parent component.
- Define an output property in the child component using the @Output() decorator and emit events using EventEmitter.
Let us look at the sample code below, which will give you an overview of parent-to-child and child-to-parent communications.
Parent Component
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h1>Parent Component</h1>
<input [(ngModel)]="parentMessage"/>
<p>{{ childMessage }}</p>
<app-child [message]="parentMessage" (notify)="onNotify($event)"></app-child>`
})
export class IOParentComponent {
parentMessage = 'Message from parent';
childMessage ="";
onNotify(message: string) {
this.childMessage =message;
}
}
Child Component
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h2>Child Component</h2>
<p>{{ message }}</p>
<input [(ngModel)]="childMessage"/>
<button (click)="notifyParent()">Notify Parent</button>
`
})
export class IOChildComponent {
@Input() message: string ='';
@Output() notify = new EventEmitter<string>();
childMessage: string ='Message from child';
notifyParent() {
this.notify.emit(this.childMessage);
}
}
Services (Cross-Component Communication) using RxJS Observables and Subjects
- Create a service that can be injected into the components needing to communicate.
- The service acts as a shared source of data and functionality.
- Components can subscribe to data streams or invoke methods provided by the service to communicate with each other.
Let us take a look at the example
Shared Service
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class DataService {
private dataSubject = new Subject<string>();
setData(data: string) {
this.dataSubject.next(data);
}
getData() {
return this.dataSubject.asObservable();
}
}
Component 1
import { Component } from '@angular/core';
import { DataService } from './dataservice.service';
@Component({
selector: 'app-scomponent1',
template: ` <h1>Component 1</h1>
<input type="text" [(ngModel)]="message">
<button (click)="sendMessage()">Send Message</button>
<app-component2>/</app-component2>`
})
export class SComponentOne {
message: string="";
constructor(private dataService: DataService) { }
sendMessage() {
this.dataService.setData(this.message);
}
}
Component 2
import { Component } from '@angular/core';
import { DataService } from './dataservice.service';
@Component({
selector: 'app-component2',
template: `
<h1>Component 2</h1>
<p>{{ receivedMessage }}</p>
`
})
export class SComponentTwo {
receivedMessage: string ='';
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(message => {
this.receivedMessage = message;
});
}
}
The below reference link explains the Mediator and Service Bus approaches for component communication in Angular.
Component communication in Angular for Senior devs by 'iamprovidence'
These are some of the commonly used methods for component communication in Angular. The choice of method depends on the specific requirements of your application and the relationship between the components involved.