Different Ways to share Data in Angular

Different Ways to share Data in Angular

When building an Angular application, it's common to break it down into smaller components to keep the code manageable. However, when working with smaller components, you may need to share data between them. To do this, it's important to first define the relationship between the components. Once you have a clear understanding of the relationship, you can choose the most appropriate method to share the data.


=> Using @Input @Output decorator for Parent Child Components

=> Using Services

=> Using View Child

=> Using State Management Libraries i.e Ngrx

=> Using @ViewChild property


Using Input and Output Decorators:

The @Input and @Output decorators are used to pass data between components that have a parent-child relationship. @Input allows a parent component to pass data down to a child component, while @Output allows a child component to emit an event to the parent component.

Use @Input when you need to pass data down from a parent component to a child component. This approach is useful when you want to reuse a child component in different parts of your application.

Use @Output when you need to emit an event from a child component to a parent component. This approach is useful when you want to notify the parent component of a change that occurred in the child component.


Parent component HTML:


<app-child
[data]="parentData"
(event)="parentMethod($event)">
</app-child>         

Parent component TS:


public parentData: any = { name: 'John', age: 30 }; 

public parentMethod(event: any): void { 

console.log('Event received from child:', event);

}         

Child component TS:


@Input() data: any; 
@Output() event: EventEmitter<any> = new EventEmitter<any>(); 

public childMethod(): void { 
  this.event.emit('Event data from child');
 }         

Using a Shared Service


Services are used to share data between components that do not have a parent-child relationship. By creating a shared service, you can keep your data centralized and easily accessible by any component that needs it.

Use services when you need to share data between components that are not directly related, or when you want to avoid passing data through several layers of components.



import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable() export class DataService {
 
private data$: BehaviorSubject<any> = new BehaviorSubject<any>({});

public getData(): Observable<any> { 
  return this.data$.asObservable();
 } 
  
  public setData(data: any): void { 
  this.data$.next(data);
     }
}         

Component TS:


import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service'; 

@Component({ selector: 'app-my-component', template: ` 
<div>{{ data.name }} is {{ data.age }} years old.</div>
<button (click)="updateData()">Update Data</button> `,
 })
 
export class MyComponent implements OnInit { 

public data: any = {};
 
constructor(private dataService: DataService) {}

ngOnInit(): void { this.dataService.getData().subscribe((data) => { 

this.data = data;
     }
   );
}

public updateData(): void {
 
this.dataService.setData({ name: 'John', age: 30 });
        
 }
      
}        


Using NgRx


NgRx is a state management library for Angular applications. It provides a way to manage application state in a centralized location and allows for easy data sharing between components.

Use NgRx when you need to manage complex application state or when you want to keep your data and business logic separate from your components.


// app.module.ts 
import { StoreModule } from '@ngrx/store'; 
import { counterReducer } from './counter.reducer'; 
@NgModule({ 
imports: [ 
BrowserModule,
StoreModule.forRoot({ count: counterReducer }), ], 
bootstrap: [AppComponent], 
})

export class AppModule {} 

// counter.reducer.ts 
import { createReducer, on } from '@ngrx/store';
import { increment, decrement } from './counter.actions'; 
export const counterReducer = createReducer( 
0,
on(increment, (state) => state + 1), 
on(decrement, (state) => state - 1) ); 

// counter.actions.ts 

import { createAction } from '@ngrx/store'; 
export const increment = createAction('Increment'); 
export const decrement = createAction('Decrement');         

Component TS:


import { Component } from '@angular/core'; 
import { Store } from '@ngrx/store'; 
import { increment, decrement } from './counter.actions'; 
@Component({ 
selector: 'app-counter', 
template: ` 
<div>Count: {{ count$ | async }}</div> 
<button (click)="increment()">Increment</button> 
<button (click)="decrement()">Decrement</button> 
`, }) 

export class CounterComponent { 
public count$ = this.store.select('count'); 

constructor(private store: Store<{ count: number }>) {} 

public increment(): void { 
this.store.dispatch(increment()); 
} 

public decrement(): void { 
this.store.dispatch(decrement()); 
  } 
}        

Using Local Storage or Session Storage


Local storage is a browser API that allows you to store key-value pairs in the user's browser. It can be used to store small amounts of data that need to persist between page reloads.

Use local storage when you need to store small amounts of data that need to persist between page reloads, such as user preferences or login information.


import { Component, OnInit } from '@angular/core'; 
@Component({ 
selector: 'app-my-component', 
template: ` 
<div>{{ data.name }} is {{ data.age }} years old.</div> 
<button (click)="updateData()">Update Data</button> `
, })
 
export class MyComponent implements OnInit { 
public data: any = {}; 
ngOnInit(): void { 
const data = JSON.parse(localStorage.getItem('data') || '{}'); 
this.data = data; 
}
 
public updateData(): void { 
const newData = { 
name: 'John',
 age: 30 
};
 
this.data = newData; 

localStorage.setItem('data', JSON.stringify(newData)); 
  } 
}        

Using View Child property


@ViewChild is used to access the properties and methods of a child component from the parent component. This approach is useful when you need to get data from a child component that is several levels deep in the component hierarchy.

Use @ViewChild when you need to access the properties and methods of a child component from the parent component. This approach is useful when you need to get data from a child component that is several levels deep in the component hierarchy.


Sure, here's an example of how to share data using @ViewChild


// child.component.ts 

import { Component, Input } from '@angular/core'; 
@Component({ 
selector: 'app-child', 
template: ` 
<div> <h2>{{ title }}</h2> </div> 
` 
})
 
export class ChildComponent { 

@Input() title: string; 

public childMethod() { 

console.log('Child method called');
   }
 } 

// parent.component.ts 

import { Component, ViewChild } from '@angular/core'; 
import { ChildComponent } from './child.component'; 
@Component({ 
selector: 'app-parent', 
template: ` 
<div> <button (click)="parentMethod()">Parent Method</button> 
<app-child #childComponent [title]="title"></app-child> </div> 
` }) 

export class ParentComponent { 

@ViewChild('childComponent') child: ChildComponent; 
public title = 'Child Component Title'; 

public parentMethod() { 
console.log('Parent method called'); 
this.child.childMethod(); 
  }
 }         


These are just a few examples of how you can share data between components in Angular. Depending on your use case, some approaches may be more appropriate than others. The Input and Output decorators are the simplest way to share data between parent and child components, while using a shared service provides more flexibility and allows you to share data between any components in your application. State management libraries like NgRx provide even more powerful tools for managing and sharing application data, but may come with a steeper learning curve. Finally, using local storage or session storage can be a good option for sharing small amounts of data between components, but may not be suitable for larger amounts of data or more complex use cases.




Sébastien Cappon

Développeur d'applications Java-Angular

1 年

Thank you so much for those clear explanations.

just took a look at your LinkedIn post, and it's fantastic to see you sharing Angular tips for web development and frontend development. Sharing knowledge like this is incredibly valuable to the community, and it helps everyone grow. Keep up the great work! For more information visit https://www.dhirubhai.net/feed/update/urn:li:activity:7108354129038630912

要查看或添加评论,请登录

Mubeen Chughtai的更多文章

社区洞察

其他会员也浏览了