Share Data Between Angular Components through View Child and Service
Posted By : Nitesh Kumar Yadav | 29-Jun-2022
Methods to Share Data Between Angular Components through @ViewChild and Service
----------------------------------------------------------------------------------------------------------
1.Using @ViewChild decorator =>
=======================
The @ViewChild decorator help to access a directive, child component, and the DOM element from a component class. ViewChild allows one component to be injected into another, giving the parent access to its attributes and functions.
===================
parent.component.ts
===================
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-parent',
template:
'<button (click)="getData()">Click</button><br/><app-child></app-child><p>{{data}}</p>',
})
export class ParentComponent {
data: string = '';
@ViewChild(ChildComponent) child: ChildComponent;
constructor() {}
getData(): void {
this.data = this.child.childData;
}
}
==================
child.component.ts
==================
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
template: '',
})
export class ChildComponent implements OnInit {
childData: string = 'data passing from child to parent';
constructor() {}
ngOnInit(): void {}
}
=======================================================================
=======================================================================
2. Using a Service =>
=================
In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a current message variable to handle this data stream as an observable that will be used by the components. Lastly, we create a function that calls next on the BehaviorSubject to change its value.
The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the current message observable and set its value equal to the message variable.
===================
parent.component.ts
===================
import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../subject-in-service.service';
@Component({
selector: 'app-parent',
template: '{{data | json}}<app-child></app-child>',
})
export class ParentComponent implements OnInit {
constructor(private Service: MyServiceService) {}
data: string[] = [];
ngOnInit(): void {
this.Service.currentData.subscribe((e) => this.data.push(e));
}
}
====================
MyService.servive.ts
====================
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class MyServiceService {
private dataSource = new BehaviorSubject<string>('Default Data');
currentData = this.dataSource.asObservable();
constructor() {}
updateData(data: string) {
this.dataSource.next(data);
}
}
==================
child.component.ts
==================
import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../subject-in-service.service';
@Component({
selector: 'app-child',
template: '',
})
export class ChildComponent implements OnInit {
constructor(private Service: MyServiceService) {}
ngOnInit(): void {
this.Service.updateData('This data is updated from child');
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Nitesh Kumar Yadav
Nitesh has more than 1.5 years of experience as a Front-End developer with hands-on experience in Angular and other front-end technologies framework. He is hardworking and Sincere towards his work.