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

Issue with Angular2 wysiwyg component failing to submitThe Angular2

I'm currently in the process of familiarizing myself with angular2 by developing a sleek wysiwyg component. However, I seem to have reached an obstacle at this point. Below is the code I've been working on: The form that I am utilizing for testi ...

Connecting to a port in node.js is not possible

Currently, I am using port 4200 for my Angular application and port 3000 for my Node.js server. However, I am facing an issue where when I run the Angular application, the Node.js server does not work and I encounter a "Connection refused" problem. Can a ...

Typescript and RxJS: Resolving Incompatibility Issues

In my development setup, I work with two repositories known as web-common and A-frontend. Typically, I use npm link web-common from within A-frontend. Both repositories share various dependencies such as React, Typescript, Google Maps, MobX, etc. Up until ...

What steps do I need to follow to write this function in TypeScript?

I am encountering a problem when building the project where it shows errors in 2 functions. Can someone please assist me? The first error message is as follows: Argument of type 'IFilmCard[] | undefined' is not assignable to parameter of type &a ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

Exploring the Integration of Angular 5 with Firestore for Working with Nested

I have a firestorm collection that follows this specific structure: USERID { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354150464175415046411b565a58">[email protected]</a>" name: "John Doe" ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

Component does not detect change when the same number is sent as input

Let me paint you a picture: I have this nifty component, set up with the OnPush strategy, that showcases a PDF document, sliding through pages one by one, and granting users the ability to smoothly glide through pages and jump to specific ones. It even of ...

The object parameter is not being bound properly in the integration of Spring Boot and Angular

I am attempting to make an HTTP POST request to an API created in Spring Boot from an Angular app. The API expects an object as a parameter. When I execute the URL with Postman using form-data or urlencoded parameters, the request finishes successfully. Ho ...

Steps for storing API information in localStorage:1. Retrieve the API data

My app is running sluggish due to the excessive API calls for information retrieval. To optimize performance, I want to create a unified object containing all the data that can be shared across pages and accessed from localStorage, thus enhancing the app ...

Ways to keep information hidden from users until they actively search for it

Currently, I have a custom filter search box that is functioning correctly. However, I want to modify it so that the data is hidden from the user until they perform a search. Can you provide any suggestions on how to achieve this? Below is the code I am u ...

Exploring Architectural Designs in Angular2: Redux, Flux, Reactivity, RxJS, Ngrx, MVI, and More

Isn't it annoying how all these library and framework names start with R/N or sound so similar? react/redux | flux | ngrx | @ngrx/store | RxJS/ReactiveX | MVI | .... Can anyone make sense of this chaos? I'm trying to understand, please help me ...

How to convert the return value of a function into a string in Angular 2

I am hoping to place the returned value within this markup: <h2>{{getSelectedUserName}}</h2> Below is the function I intend to utilize, which will return a string: public getSelectedUserName(): string { let firstName = this.selectedUser. ...

Tips for extending the duration of $ionicLoading.show() to meet a specified time limit

For the ionic app I'm working on, I have content that loads dynamically when a user clicks. To keep things looking smooth, I use $ionicLoading.show() before calling the API and $ionicLoading.hide() once the response is received. I'd like to ensu ...

The functionality of Angular 4 routing breaks down when attempting to access a direct URL path

Currently, I am working on an Angular 4 application that has numerous routes. The issue I am encountering is fairly straightforward to comprehend. All routing functions as expected within the app; however, a problem arises when accessing a specific URL dir ...

Issue with Angular 6.1.0: Scroll position restoration feature malfunctioning

RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }) In the latest version 6.1.0, there is a new feature that aims to restore the scroll position after navigation. Unfortunately, I encountered an issue where the scroll restorat ...

Create a simulated class to serve as a property within a service

Currently, I'm working on an Ionic application and have created an AlertService class with two properties: messageAlert: Alert; errorAlert: Alert; The Alert class belongs to the Ionic framework, so I cannot modify it. To mock the Alert class, I came ...

Encountering a CORS issue when utilizing passport-facebook for Facebook authentication in my MEAN application

I'm currently working on implementing a Facebook login feature for my web app, built with express js, mongodb, and angular 2. The client-side of the app is generated using angular-cli (running on port 4200), and I'm utilizing the proxy config pr ...