Whenever the route changes in Angular, the components are duplicated

Whenever I switch routes in my Angular application, such as going from home to settings and back to home, all the variables seem to be duplicated from the home page and are never destroyed.

I noticed that I created a loop in the home component that displays a timestamp. Each time I perform the mentioned test case, the timer keeps printing more and more information.

Is there a way to prevent this unwanted behavior?

interface-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: InterfaceComponent,
    children: [
      {
        path: 'home', component: HomeComponent
      },
      {
        path: 'settings', component: SettingsComponent
      },
      {
        path: '',
        redirectTo: '/home',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  }
];

Answer №1

The Angular documentation explains:

Before Angular destroys the directive or component, cleanup should be done in ngOnDestroy(). This involves unsubscribing from observables and detaching event handlers to prevent memory leaks. Refer to the section on cleaning up during instance destruction for more information.

As a result, it is recommended to set all class variables to null in the OnDestroy life cycle hook as shown below:

ngOnDestroy() {
    this.someVariable = null;
}

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

Navigating back to the starting point

I'm experiencing an issue while trying to navigate using the Router.navigate method. Despite following all instructions meticulously, whenever I attempt to route via API, it reloads the root page. Within my RootComponent implementation, I am utilizin ...

The technique for accessing nested key-value pairs in a JSON object within an Angular application

After receiving the response from the backend, I have retrieved a nested hash map structure where one hash map is nested within another: hmap.put(l,hmaps); //hmap within hmap When returning the response to the frontend, I am using the ResponseEntity meth ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Learning the process of configuring neo4j connection details without relying on environment variables

Is there a way to specify the database connection in code using the Drivine neo4j driver without relying on environment variables? ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...

Creating a custom theme in MUI v5 by modifying ColorPartial members

I am seeking a solution to override certain members within PaletteOptions. My goal is to switch the type of grey from ColorPartial to PaletteColorOptions in order to include additional members. This was my attempt at implementing the necessary code: decl ...

Integrate AngularJS service with Angular framework

Attempting to utilize the $log service within an angular 2 app, it seems that the following steps are necessary: Set up a module that includes the service you wish to inject. Utilize UpgradeAdapter's upgradeNg1Provider method. Therefore, I proceede ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

Access an Angular 2 component through an email hyperlink including querystring parameters

I need to create a deep link with query string parameters for a component, so that when the link is clicked, it opens up the component in the browser. For example: exmaple.com/MyComponent?Id=10 I want to include a link in an email that will open the com ...

Adding a project to TFS source control using Visual Studio Code: a step-by-step guide

Looking for guidance on adding an Angular 4 project developed with Visual Studio Code (version 1.18.0) to TFS source control. I've already installed the TFS extension (version 0.6.0) in Visual Studio Code, but unsure how to map the project folder to T ...

Leveraging ArangoJS Driver within an Angular2 web platform

Currently, I am in the process of working on a project that involves Angular2 and Typescript (v1.8.10). Our aim is to incorporate data from an ArangoDB database into the web application. Ideally, I would like to utilize the arangojs driver for this task. H ...

Issue with running tests on Angular Material components causing errors

Running ng test on my Angular 8 project with Angular material components is resulting in multiple failures. The issue seems to be related to missing test cases for these scenarios. DeleteBotModalComponent > should create Failed: Template parse errors: & ...

Mapping objects in Typescript to create a union of objects

I have been working on some TypeScript code and I seem to be having trouble getting it to work as expected. It would be greatly appreciated if someone could help me understand what I'm doing wrong or suggest a different approach. Let's assume I ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Using multiple instances of ngrx stores within a single application

Can one create a unique instance store for each component instance, similar to services declared in the providers array of the component decorator? ...

Tips for running batch files prior to debugging in VS Code

Currently, I am working on a project using Typescript, nodeJS, and VS Code. When it comes to debugging in VS Code, I have set up configurations in my launch.json file. { "type": "node", "request": "launch", "name": "La ...

Steps to resolve the "Module not found" error when executing the npm run build command

When running the npm run build command in my application, I encountered a module not found error shown below: npm WARN npm npm does not support Node.js v16.17.0 npm WARN npm You should probably upgrade to a newer version of node as we npm WARN npm can&apos ...

When you use the 'Deploy to Azure' extension in VS Code to deploy your Angular App, the environment.ts settings get updated

While attempting to deploy my Angular App (mysite.com) to Azure using the 'Deploy to Azure' extension in VS Code, I encountered an issue. The api url specified in the environment.ts file (myapi.com) is not being utilized when accessed within the ...