Endure the class attribute in Angular 5

My SearchComponent has a route (/search) and SearchDetailComponent has a route (/search-detail:id).

In the SearchComponent, there is a searchbox (input field) where I can type any text to start a search.

After loading the search results and navigating to the SearchDetail page, I want to store the search term I entered into the searchbox. However, this should only happen after returning from the Detail page. This means that when I navigate back from the detail page, the same text I searched for should be displayed in the searchbox.

The searchbox should remain empty while navigating to the search site from any other page.

Does anyone have an example or suggestion on how to implement this?

Answer №1

One way to persist data is by utilizing a Service or localStorage/Session Storage.

localStorage and sessionStorage serve the same purpose and have similar APIs. However, with sessionStorage, the data is only stored until the window or tab is closed, whereas with localStorage, the data remains until cleared manually by the user or by the application.

I recommend using @ngx-pwa/local-storage Async local storage for Angular.

For Angular 5:

npm install @ngx-pwa/local-storage@5

Register it in your RootModule

import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule,
    ...
  ]

Inject and utilize

import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

Usage

let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {});

When navigating back and forth, adjust values using setValue() or patchValue(), both of which update the value in the form control of FormGroup.

Service
Develop a Service and add it to an Angular module instead of a component.

If you need a dependency instance shared globally to maintain state across the application, configure it within NgModule.

You can use either Subject or BehaviorSubject to achieve this.

  1. Using Subject

  2. Using BehaviorSubject

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

Getting the mssql output in Protractor using VSCode

I recently tried running the code below and it seems like the connection is established successfully. However, I'm unable to see any output. Is there a way to view the query result? I am still learning about Protractor, NodeJS, and MSSQL connections. ...

Is there a way to dynamically exclude files from the TypeScript compiler?

Currently, I am in the process of setting up a node/typescript server for a real-time application. Both my server and client are located within the same folder. My goal is to exclude "src/client" from the typescript compiler when executing the "server:dev ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...

The 'firestore' property is not found within the 'Firebase' type

I'm currently working on retrieving the precise time a document is generated. To achieve this task, I have included the following imports: import { Firebase } from '@ionic-native/firebase/ngx'; import { AngularFirestore } from '@angul ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

An Angular module downloaded from npm seems to be lacking the required @NgModule declaration

There seems to be a missing @NgModule and @Directive declarations in an NPM module, even though they exist in the source code on Github. This is causing an issue with importing a directive for databinding from an HTML attribute. I am attempting to utilize ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Issue with Next.js hook: Uncaught TypeError - Unable to define properties of undefined (setting 'type')

Encountered an error while attempting to build my nextjs app. Strangely, this error wasn't present in the previous version of the app. I didn't make any changes to the config files, just added a few animation libraries and that's all, along ...

How to safely add multiple objects to an array in TypeScript & React without replacing existing objects - Creating a Favorites list

I'm in the final stages of developing a weather application using TypeScipt and React. The last feature I need to implement is the ability for users to add queried locations to a favorites list, accessed through the "favorites" page. By clicking on a ...

Error Encountered in Cypress: "Tried to wrap warn but it is already wrapped"

Objective: Utilize Cypress and Typescript to test for warnings and errors on the console. Error Encounter: An attempt was made to wrap warn, which is already wrapped. Snippet: describe.only("Unauthenticated User", () => { it("No C ...

The NgbTooltip does not activate when hovering over a <td> cell

I'm currently facing an issue with implementing ngbTooltip on <table> elements. Initially, I had trouble with <th>, but that was resolved by using the container attribute after referring to this helpful post. The main challenge arises ...

The Vercel public domain is not functioning as expected

After successfully developing a next.js application with user auth using NextAuth and deploying it to Vercel, I encountered an issue related to the notifications page functionality. The problem arises when the app checks for an active session; if none is f ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

Best practices for incorporating CSS and JS files into an Angular deployment

I am currently in the process of integrating an Admin Template that I previously used in a traditional PHP application into a new Angular project. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel= ...

Combining normal imports with top-level await: A guide

Is it possible to simultaneously use imports (import x from y) and top-level awaits with ts-node? I encountered an issue where changing my tsconfig.compilerOptions.module to es2017 or higher, as required by top-level awaits, resulted in the following error ...

Creating a test scenario for a combineLatest Observable using marbles

I am working with an observable that combines two Observable<boolean> using the "or" operation with combineLatest. interface LoadingEventEmitter { isLoading$: Observable<boolean> } export class LoadingService { isLoading$: Observable<bo ...

The data type 'T' cannot be assigned to type 'T'

Having extensive experience as a javascript developer, I recently delved into learning C# as my first statically typed language. My upcoming project involves using TypeScript, so I've been refreshing my knowledge on it. Below is the code I have writt ...

The parameter type '(req: Request, res: Response, next: NextFunction) => void' does not match the type of 'Application<Record<string, any>>'

I'm currently working on an Express project that utilizes TypeScript. I have set up controllers, routers, and implemented a method that encapsulates my controller logic within an error handler. While working in my router.ts file, I encountered an err ...