Aditya Mohite, Author at Perficient Blogs https://blogs.perficient.com/author/amohite/ Expert Digital Insights Tue, 23 Jan 2024 14:22:29 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png Aditya Mohite, Author at Perficient Blogs https://blogs.perficient.com/author/amohite/ 32 32 30508587 Different Methods to Share Data Between Components in Angular – Part 2 https://blogs.perficient.com/2024/01/23/different-methods-to-share-data-between-components-in-angular-part-2/ https://blogs.perficient.com/2024/01/23/different-methods-to-share-data-between-components-in-angular-part-2/#respond Tue, 23 Jan 2024 14:11:51 +0000 https://blogs.perficient.com/?p=354471

Welcome back to different methods to share data between components in Angular.  In this post, we’ll continue with the remaining ways to share data in Angular components.

3. Sharing data using Routing Parameters or Query Parameters.

Angular’s routing module allows for passing data between components by utilizing route parameters.
Example:
Route Conf

Route Parent

We can pass data through the URL and retrieve it in the target component using the ActivatedRoute module.

4. Sharing data using State Management with Reactive Extensions (RxJS).

When dealing with complex data sharing requirements that lack a direct connection, such as siblings, grandchildren, etc. using a state management solution like RxJS can be highly beneficial.

RxJS provides observables and subjects that facilitate reactive programming and enable efficient data sharing between components. Here, again we use services but with RxJS approach. You can also use a regular RxJS Subject for sharing data via the service, but here’s why I prefer BehaviorSubject.

  • It will always return the current value on subscription – there is no need to call “onNext”.
  • It has a “getValue()” function to extract the last value as raw data.
  • It ensures that the component always receives the most recent data.

Shared Service File:
Rxjs Service

In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable to handle this data stream as observable that will be used by the components. Lastly, we create a function that calls next on the BehaviorSubject to change its value.

Parent Component
Rxjs Parent

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.

Child Component / Sibling Component:
Rxjs Child

Now if we create a function in any one of these components that changes the value of the message. When this function is executed the new data automatically broadcast to all other components.

5. Sharing data using LocalStorage or SessionStorage

If you need to preserve data across sessions or between various parts of your application, you can store data in the browser’s “localStorage” or “sessionStorage”. However, note that these methods are limited to string-based data.

Local storage is client-side storage for web applications. It stays there as long as it’s not cleared unlike session storage, which lasts for the current browser tab session. Local storage provides up to 5MB of storage, allocated separately for each domain. For example, local storage for the website www.facebook.com will be different from www.twitter.com.

Let’s create a service file named “LocalService” to store data in local storage.
Localstorage Service

To use the LocalService in component file, you need to inject it by importing it into your required component file by creating an instance in the constructor method.
App component:
Localstorage App

After the app component gets loaded it will set value of “id” in local storage via “LocalService” file “saveData()” method, and we can get the same key value by clicking on “getIdFromLocal()” method by calling “getData()” method from “LocalService” file.

The local storage API provides a couple of methods to store, retrieve, remove, and clear the storage.

For Example:

  1. localStorage.setItem(‘token’,’xhja787′)
  2. localStorage.getItem(‘token’)
  3. localStorage.removeItem(‘token’)
  4. localStorage.clear()

Note: localStorage only stores string values. To store objects or arrays, you need to use JSON.stringify to convert them into a string first.

Thus, we can use Local Storage or Session Storage in Angular to share data between components.

Conclusion

In this article, we have explored different methods for sharing data between components in Angular. From simple parent-child communication using input and output properties to advanced solutions like state management with RxJS, you now have a range of options to choose from based on your application’s complexity.

Remember to select the method that best fits your use case and maintain consistent data-sharing practices throughout your application. By adopting appropriate data-sharing techniques, you can ensure efficient component communication and build robust Angular applications.

]]>
https://blogs.perficient.com/2024/01/23/different-methods-to-share-data-between-components-in-angular-part-2/feed/ 0 354471
Different Methods to Share Data Between Components in Angular – Part 1 https://blogs.perficient.com/2024/01/23/different-methods-to-share-data-between-components-in-angular-part-1/ https://blogs.perficient.com/2024/01/23/different-methods-to-share-data-between-components-in-angular-part-1/#respond Tue, 23 Jan 2024 12:44:05 +0000 https://blogs.perficient.com/?p=354347

Introduction

Sharing data between components in Angular is a common requirement in complex applications having multiple components. Angular provides several methods to accomplish this task effectively and efficiently. In this blog, we will examine different methods to share data between components. We will cover methods going from easy to cutting edge, permitting you to pick the one that suits your utilization case.

Here, I will assume that you already did the project setup, and you know the basics of Angular like how two-way data bindings work, import and export of files. Methods to share data between components are as follows:

1.  Parent-Child Communication using Input and Output Properties.

Using input properties, you can send data from the parent component to the child component and use output properties to get data from the child component to the parent component.

a.  Parent to Child using @Input() decorator.

Input properties allow you to pass data from a parent component to its child component. By defining a property in the child component with @Input() decorator, you can receive the data from the parent component.
Example:
Input Parent To Child

Input Childcomp
Here we will get “Hello message from parent!” message from the parent component into the child component inside the data variable.

b. Child to Parent using @Output() and EventEmitter

Another way to share data is to emit data from the child, which can be listened by the parent. This approach is ideal when you want to share data changes that occur on things like button clicks, form entries, and other user events.
Example:
Output Parent
In the parent, we create a function to receive the message and set it equal to the message variable.

Output Child

In the child, we declare messageEvent variable with the Output decorator and set it equal to a new event emitter. Then we create a function named sendMessage that calls emit on this event with the message we want to send. Lastly, we create a button to trigger this function.
The parent can now subscribe to this messageEvent that is outputted by the child component, and then run the receiveMessage function whenever this event occurs.

c. Child to Parent using ViewChild

Another method to share data from child to parent is ViewChild. ViewChild allows one component to be injected into another, giving the parent access to its attributes and functions.

One issue with ViewChild is that child won’t be available until after the view has been initialized. This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.

Example:
Viewchild Parent

Viewchild Child

2. Sharing Data with a Service

Another powerful method to share data between components is by using a shared service. A shared service acts as a central point for data manipulation and communication between components. Components can share data by injecting and accessing the service.

Example:
Service file.
Service Servicefile

Service Compa

Service Compb

Here, we set the property from “Component A” by calling shared service file setSharedData() method in it and get the data from the same shared service file in “Component B” by calling getSharedData() method.

So, using this way you can share data between sibling components in Angular.

Up Next

In the next post, we’ll continue with more ways to share data between components in Angular.

]]>
https://blogs.perficient.com/2024/01/23/different-methods-to-share-data-between-components-in-angular-part-1/feed/ 0 354347