In Angular, there are several ways to enable communication between components, depending on their relationship.
- Parent-Child Relationship
- using @Input and @Output and EventEmitter.
- using Parent Accessing Child Methods (@ViewChild)
- No Parent-Child Relationship
- using service by storing value into variables.
- using Subject & SubjectBehaviour of RXJS.
- using routing i.e. navigating from one component to another with query param.
- we can store data in local Storage or session Storage and read data wherever we need.
1. Parent to Child Communication
Using @Input Decorator => Parent to Child communication
Using @Output and EventEmitter => Child to Parents communication
<p>one works!</p>
{{item}}
{{item2}}
export class OneComponent {
@Input() item=0;
@Input() item2='';
}
<p>two works!</p>
<app-three (updateDataEvent)="updateData($event)"></app-three>
{{data}}
export class TwoComponent {
data ='';
updateData(item:string){
console.warn(item)
this.data=item;
}
}
<p>three works!</p>
<input type="text" #box>
<button (click)="updateDataEvent.emit(box.value)">submit</button>
export class ThreeComponent {
@Output() updateDataEvent = new EventEmitter<string>();
}
2. Siblings or Unrelated Components: Use a shared service.
=> Components that do not share a direct parent-child relationship.
=>Using a Shared Service
Create a service with a shared data stream (e.g., Subject or BehaviorSubject) to facilitate communication.
Create a service with a shared data stream (e.g., Subject or BehaviorSubject) to facilitate communication.
Shared Service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SharedService {
private messageSource = new BehaviorSubject<string>("default message");
currentMessage = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message);
}
}
Component A (Sender):
constructor(private sharedService: SharedService) {}
sendMessage() {
this.sharedService.changeMessage("Hello from Component A");
}
Component B (Receiver):
typescript
Copy code
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.sharedService.currentMessage.subscribe(message => {
console.log(message); // "Hello from Component A"
});
}
Comments
Post a Comment