The values of reusable components persist across page2 and all other subsequent pages

In my component labeled as search-component, the HTML snippet is displayed below:


        <form class="form-horizontal form-material" (ngSubmit)="Search()" id="carsearch" [formGroup]="bookCarForm"
            novalidate>
            <div class="row">
                <div class="col-sm search-input-align">
                    <input [owlDateTime]="dt1" [min]="min" [owlDateTimeTrigger]="dt1" class="form-control"
                        formControlName="start_datetime" placeholder="Start Date & Time">
                    <owl-date-time #dt1></owl-date-time>
                    <span class="input-group-addon"><i class="fa fa-calendar fa-search-align"></i></span>
                </div>

                <div class="col-sm search-input-align">
                    <input [owlDateTime]="dt2" [min]="min" [owlDateTimeTrigger]="dt2" class="form-control"
                        formControlName="end_datetime" placeholder="End Date & Time">
                    <owl-date-time #dt2></owl-date-time>
                    <span class="input-group-addon "><i class="fa fa-calendar "></i></span>
                </div>
                <div class="col-sm search-input-align">
                    <div class="toggle" (click)=toggleTextBox()>
                        <input type="checkbox" class="check" >
                        <b class="b switch"></b>
                        <b class="b track"></b>
                    </div>
                    <h4 id="door-delivery">Door Delivery</h4>
                </div>
                <div class="col-sm search-input-align address">
                    <div *ngIf="!visability">
                        <input class="form-control " formControlName="Enter_address" type="text" placeholder="Enter Address"
                            >
                    </div>
                    <div *ngIf="visability">
                        <select formControlName="p_location" class="form-control selectpicker" id="select-city" >
                            <option data-tokens="" disabled>
                                <h2>select any one </h2>
                            </option>
                            <option data-tokens="Delhi">
                                <h2>Hebbal</h2>
                            </option>
                            <option data-tokens="Mumbai">
                                <h2>Yelahanka</h2>
                            </option>
                            <option data-tokens="hyderabad">
                                <h2>BTM</h2>
                            </option>
                        </select>
                    </div>
                </div>
                <div class="col-sm search-input-align btn-book-now">
                    <button type="submit" [disabled]="bookCarForm.invalid" class="btn btn-primary align-items-center btn-align">Book
                        Now</button>
                </div>
            </div>
        </form>
    

In the file search-component.ts, the code snippet looks like this:

@Output() searchValues = new EventEmitter(); 
this.storage.set("values", this.Search.value);//storing values in local storage
this.searchValues.emit("values");

This particular search-component can be used multiple times. Currently, I am using this form on Page1 to select values and redirecting to page2. On page2, I am also utilizing the same form. However, the challenge I'm facing is that the values selected on page1 are not carried over to page2 despite attempting to use Event Emitter. I referred to a resource here, but it did not resolve my issue. Could someone suggest the most effective approach to achieve this outcome? Your assistance would be greatly appreciated.

Answer №1

To implement a service called stored-data-service.ts, follow these steps:

import {Component, Injectable} from 'angular2/core'
import {BehaviorSubject, Observable} from 'rxjs';

@Injectable()
export class StoredDataService {
  values:any;
  values$:BehaviorSubject<any> = new BehaviorSubject('');
  constructor(){}

  setValues(values){
   this.values = values;
   this.values$.next(values);
  }
} 

Next, include it in your app.modules.ts file by importing it:

import { StoredDataService } from "./stored-data-service.ts";

Then add it to the providers array within the NgModule like so:

@NgModule({
  declarations: [
  ...],
  imports: [
  ...],
  providers: [
  StoredDataService],
  bootstrap: [AppComponent]
})

Now, inject it into your component search-component.ts by including it in the constructor:

constructor (public storedDataService: StoredDataService){}

Use the service to store data using the following method:

this.storedDataService.setValues(this.Search.value);//storing values in local storage

To retrieve the stored data anywhere in your code, you need to subscribe to values$:

 const subscription = this.storedDataService.values$.subscribe( (values) => {
 //set a local variable here storing values in you component
 //...
 this.values = values
 console.log (values);
})

If you plan to use the StoredDataService in another component, remember to inject it in the constructor and subscribe to values$. This way, whenever there is a change in the stored data, all subscribed components will get the updated value.

EDIT

Be sure to use BehaviorSubject and subscriptions as shown in the code for proper functionality

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Design your own Angular 2 Directive for effortless element dragging!

My goal is to develop a custom directive in Angular 2 that enables the user to drag an HTML Element based on its x position. I have drafted some pseudo code to demonstrate what I think might work, however, my experience with directives is limited and I ...

Accessing dynamic data beyond the subscribe method function

Having some trouble creating a function that retrieves an object from a service using an external API. I'm struggling to get it functioning properly. FetchMatchInfo (matchId : number): Match { let retrievedMatch: Match; this.matchService.Ge ...

AngularJS: The 'myInputName' property is not defined and cannot be read

Encountering an error with AngularJS: https://i.sstatic.net/TBHem.png The issue is related to the titleInput TextBox name property: @Html.TextBox("titleInput", null, new { @placeholder = @T("Message title"), @class = "form-control", ng_model = "feed.fee ...

Add adhesive dashes to the text box

I am looking to add sticky hyphens in a text input field. I have included an image illustrating my requirement. The areas that need fixing are highlighted in red. The first hyphen should appear after every three number inputs, followed by the next one afte ...

The 'innerText' property is not present in the 'Element' type. (2339)

Recently, I've been working with javaScript and I encountered some issues while writing a function. Strangely, I kept receiving error messages that I couldn't quite understand. Initially, there was a problem where every time I tried to create a j ...

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

Having trouble with VS Code on my Linux system - npm error popping up?

protons@protons-HP-EliteBook-840-G3:~/Desktop/NH_Facility_Portal_V0$ sudo npm install [sudo] password for protons: npm notice npm notice New minor version of npm available! 8.12.1 -> 8.13.2 npm notice Changelog: https://github.com/npm/cli/releases/tag ...

Angular 9: Implementing a synchronous *ngFor loop within the HTML page

After receiving a list of subjects from the server, exercises are taken on each subject using the subject.id (from the server) and stored all together in the subEx variable. Classes are listed at the bottom. subjects:Subject[] temp:Exercise[] = [] s ...

Utilize FieldPath.documentId() from Firestore to access a nested object

Let me explain the structure of my data: Each element contains a cluster object, and the cluster object includes a tags object with one or more tag objects. This setup aligns with firebase's denormalized data structure, as outlined here. We implemen ...

What is the correct way to write an asynchronous Express middleware function in Typescript?

Can anyone help me figure out how to correctly define a return value for an express middleware that utilizes async/await? I've been experimenting with different approaches but haven't found success yet. Additionally, I'm attempting to exten ...

TypeScript test framework for testing API calls in VS Code extensions

My VS Code extension in TypeScript uses the Axios library for API calls. I have written tests using the Mocha framework, which are run locally and through Github Actions. Recently, I integrated code coverage reporting with `c8` and I am looking to enhanc ...

What is the proper way to implement the coalesce function in my code?

I'm still learning about TypeScripts and other typed languages beyond just standard types. My goal is to find a more precise way to type this function, removing the any type for both parameters and the return type. The function is designed to return ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

Securely import TypeScript modules from file paths that are dynamically determined during execution

Imagine you have a structure of TypeScript code and assets stored at a specific URL, like between a CDN and a debug location. You want to import the main module and ensure the rest of the structure is imported correctly only when needed, without repeating ...

Mastering the art of throwing and managing custom errors from the server to the client side within Next.js

I'm in the process of developing a Next.js application and I am faced with the challenge of transmitting customized error messages from the server to the client side while utilizing Next JS new server-side actions. Although my server-side code is func ...

Strategies for resolving the TypeScript error code TS7009?

I am currently new to Typescript programming and in the learning phase. I encountered a problem while coding and received an error in the backend console. Here is the code snippet that caused the error: function employee(id:number,name:string) { this.i ...

Looking for a way to convert 24-hour format to minutes in Angular? I'm in need of some TypeScript code to

I am looking for Typescript code that can convert 24-hour time format into minutes. For example, when converting 1.00 it should output as 60 minutes. When converting 1.30 it should equal to 90 minutes. If anyone has the code for this conversion, p ...

Problem with Angular input field not updating after making an http request

After receiving a response from an http get request, I'm attempting to map the data with an input field but it's not working as expected. this.http.get<any>('https://localhost:9002/....../getEmail') .subscribe({ ...

What is the best way to merge three arrays of data into a single iterable array?

I am working on a function that fetches data from an API. In this process, I execute a total of 3 queries, each returning an array of data. My goal is to combine these 3 arrays into a single iterable array, where the indexes correspond to the original a ...

Using TypeScript's .map method to add a new property to an array of objects results in an error stating that the property does not

type Dog = { name: string; furColor: "brown" | "white" }; const addLocation = (animals: Dog[], location: "Italy" | "France") => animals.map((animal) => (animal.location = location)); // animal.location thr ...