Maintaining component state during route changes in Angular routing

After successfully incorporating lazy loading into my Angular application, I noticed that when I switch pages, the previously loaded page reverts back to its initial state (ngOnInit being triggered again).

{ path: '/posts', loadChildren: () => import('./posts/main.module').then(m => m.MainModule) }

Answer №1

The behavior you are observing is not related to lazy loading at all.

When a component is no longer being used in the DOM, Angular initiates the cleanup process by executing the "ngOnDestroy" method of the component (if it exists). This allows the component to perform any necessary cleanups or data saving before it is destroyed.

Therefore, when the same component is added back to the DOM, it is treated as a new instance and the "ngOnInit" method is executed again.

You can test this yourself using a simple "*ngIf". The ngIf directive will add or remove a component from the DOM based on the if-statement. However, if you use "hide", the component will remain in the DOM but simply be hidden, keeping the instance intact.

In your specific scenario, it seems that the router is responsible for adding and removing the component...

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

Which flow is best for single page applications: Implicit or Authorization Code in OpenID Connect?

OIDC offers multiple authentication flows, with Implicit and Auth Code flow being the two primary options available for SPAs. Recent discussions in the ietf mailing list suggest that Auth code flow is preferable to implicit flow due to security concerns su ...

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

Issue with Angular 4: Radio button defaults not being set

After hardcoding the value in component.ts, I am able to see the pre-selected radio button. However, when attempting to retrieve the value from sessionStorage, it does not work as expected. The value is visible in the console though. Could someone please ...

What is the definition of reusable components within the context of Angular, React, and Vue?

I've been hearing a lot about reusable components. What does this actually mean? For instance, if I want to showcase basic user information like ID, name, age, etc. Does it imply that the component is "plug and play," where you simply write the sele ...

Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; The c ...

How to Validate Ionic 2 Radio Button Selections with TypeScript

Imagine having a list like the one shown below: <ion-list radio-group [(ngModel)]="autoManufacturers"> <ion-list-header> Auto Manufacturers </ion-list-header> <ion-item> <ion-label>Cord</ion-label> &l ...

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

Assigning a custom class to the cdk-overlay-pane within a mat-select component is restricted to Angular Material version 10.2.7

I attempted the code below, but it only works for angular material 11. My requirement is to use only angular material 10. providers: [ { provide: MAT_SELECT_CONFIG, useValue: { overlayPanelClass: 'customClass' } } ] There a ...

Excessive notification events are currently causing a blockage in the Angular app

Currently, I am utilizing Angular 7 in combination with SignalR on the backend for push notifications. At certain times, an overwhelming amount of notifications flood in, causing my application to become completely unresponsive. The SignalR service compon ...

The server in Angular 4 does not pause for the http call to finish before rendering. This can result in faster loading

After implementing angular universal, I was able to render the static part of HTML via server-side rendering. However, I encountered an issue where API calls were being made and the server rendered the HTML without waiting for the HTTP call to complete. As ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

Prevent automatic submission of forms when selecting attributes in HTML forms using AngularJS

I need to create a form where users can select their branch of study. Here is the form I have designed- <form method="post" [formGroup]="formData" (click)="dataSubmit()" > <div class="form-group"> <label for="branch">Selec ...

An informative step-by-step approach to constructing Angular applications utilizing npm and TypeScript

When I first encountered Angular2, I was introduced to TypeScript, npm, and more for the very first time. I was amazed by their power, but I know I've only scratched the surface. While I can navigate through the "development mode," my ultimate goal i ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

Cross-origin resource sharing (CORS): In PHP, the response to the preflight request is not successfully passing. I am permitting

With the abundance of CORS posts already out there, I find myself adding to them in search of a solution. My dilemma involves building an angular 4 application that interacts with my php api. Locally, everything works seamlessly. However, once I upload the ...

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...