Data sharing becomes a common requirement in Angular components. The following list contains all available methods for data sharing in Angular:
The Input function enables data transmission between parent and child components.
The child component can transmit data to the parent by utilizing the EventEmitter functionality through @Output().
Example
Parent Component:
<app-child [message]="parentMessage" (childEvent)="receiveMessage($event)"></app-child> <p>From Child: {{ childMessage }}</p>
export class AppComponent {
parentMessage = "Hello from Parent";
childMessage = "";
receiveMessage(event: string) {
this.childMessage = event;
}}
Child Component:
export class ChildComponent {
@Input() message!: string;
@Output() childEvent = new EventEmitter<string>();
sendMessage() {
this.childEvent.emit("Hello from Child");
}
}
<p>From Parent: {{ message }}</p>
<button (click)="sendMessage()">Send to Parent</button>
For sharing data between unrelated components, use a service with BehaviorSubject.
Example
Shared Service:
@Injectable({ providedIn: 'root' })
export class SharedService {
private messageSource = new BehaviorSubject<string>("Initial Message");
currentMessage = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message);
}
}
Component A (Sender):
this.sharedService.changeMessage("Hello from A");
Component B (Receiver):
this.sharedService.currentMessage.subscribe(message => console.log("Received:", message));
The parent component extends its access to child component methods and properties through this feature.
Example
@Injectable({ providedIn: 'root' })
export class SharedService {
private messageSubject = new Subject<string>();
message$ = this.messageSubject.asObservable();
sendMessage(message: string) {
this.messageSubject.next(message);
}
}
Sender Component:
this.sharedService.sendMessage("Hello from Sender");
Receiver Component:
this.sharedService.message$.subscribe(message => console.log("Received:", message));
localStorage.setItem("sharedData", "Hello");
console.log(localStorage.getItem("sharedData"));
Query Params:
this.router.navigate(['/receiver'], { queryParams: { data: "Hello" } });
this.route.queryParams.subscribe(params => console.log(params['data']));
The parent component extends its access to child component methods and properties through this feature.
Example
Parent Component:
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child.childMethod());
}
Child Component:
childMethod() {
return "Data from Child";
}
Like ViewChild(), but for multiple child components.
Example
@ViewChildren(ChildComponent) children!: QueryList<ChildComponent>;
ngAfterViewInit() {
this.children.forEach(child => console.log(child.childMethod()));
}
Useful when using <ng-content>.
Example
Parent Template:
<app-child>
<p #contentRef>Projected Content</p>
</app-child>
Child Component:
@ContentChild('contentRef') content!: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.innerText);
}
For sharing data between a form control and a component.
Example
<input [(ngModel)]="sharedData">
A simple but not recommended method.
export let sharedData = "Global Data";
Access it anywhere:
import { sharedData } from './global';
console.log(sharedData);
Angular provides multiple ways to share data between components, each suitable for different scenarios. Choose the method that best fits your application's architecture and requirements to ensure efficient and maintainable code.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us