Is it Angular's practice to clear properties or arrays upon ngOnDestroy to avoid memory leaks?

Here is the code snippet in Angular 9:

employee.component.ts

  name:string;
  arr = [];

  ngOnInit() {
    this.name = "abc";
    for (let i = 0; i < 1000; i++) {
            this.arr.push(i);
          }
    }

When moving to another component using Angular routing, the employee component will be destroyed.

Should I clear the array and name property on ngOnDestroy() method to avoid memory leaks?

ngOnDestroy() {
    this.name = "";
    this.arr = [];
  }

Will Angular automatically clear the array and properties on ngOnDestroy?

Answer №1

No manual cleaning up is required for those variables since they will be automatically garbage collected. See more at this link.

Answer №2

Make sure to take care of your component subscriptions to prevent memory leaks. The garbage collector will handle most cases, but if your component is still referenced in some way, it will not be collected.

To properly handle subscriptions, utilize the ngOnDestroy lifecycle hook to unsubscribe from all observables. Here's an example:

    @Component({...})
    export class AppComponent implements OnInit, OnDestroy {
        subscriptions: Subscription[] = [];
        ngOnInit() {
            const observable1 = Rx.Observable.interval(1000);
            const observable2 = Rx.Observable.interval(1000);
            this.subscriptions.push(observable1.subscribe(x => console.log(x)));
            this.subscriptions.push(observable2.subscribe(x => console.log(x)));
        }
        ngOnDestroy() {
            this.subscriptions.forEach(subscription => subscription.unsubscribe())
        }
    }

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

What is the proper way to utilize useRef in TypeScript to assign a function to ref?

I am just diving into Typescript and I am looking to assign a function to a ref within a custom hook. My goal is for the function to remain constant throughout renders. Check out the code on CodeSandbox: https://codesandbox.io/s/918l0wro4r function runFu ...

Angular's ng -build encountered an error due to OSSL EVP being unsupported

A sneak peek into the ng --version details on my system. @angular-devkit/build-webpack 0.13.10 @angular-devkit/core 7.3.10 @angular-devkit/schematics 7.3.10 @angular/animations 7.2.15 @angular/cli ...

Managing alerts in Protractor

I encountered a challenge while trying to handle an alert using Protractor. My goal is to navigate to another page after accepting the alert, but my attempts have not been successful so far: (PS, if I remove the failing tests, all other tests work fine) (P ...

Tips for showing that every field in a typed form group must be filled out

Starting from Angular 14, reactive forms are now strictly typed by default (Typed Forms). This new feature is quite convenient. I recently created a basic login form as shown below. form = this.fb.group({ username: ['', [Validators.required ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Steps for displaying a new event on a fullCalendar

Utilizing fullCalendar to display a list of events in the following manner: this.appointments = [{ title: "Appointment 1", date: "2020-09-06", allDay: false }, { title: "Appointment 2", date: "2020 ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Using the OR operator in Angular's *ngIf directive within a component's HTML

Need help with an *ngIf statement using OR in Angular, but the second condition is not working as expected. See below for the code: <div *ngIf="router.url != '/one' || router.url != '/two'"> show something </div> Any su ...

Encountering a JS error while attempting to execute a basic HTTP request

I'm currently attempting to interact with a Gateway and decided to test out the https://www.npmjs.com/package/@types/request module. Below is the snippet of code I am trying to execute: export class OAuthAccessor { //some stuff public stat ...

Angular 9's Jasmine Mocking Provider Featuring Unique Methods and Properties

Currently, I am attempting to mimic the functionality of the angularx-social-login npm package. My goal is for the default test to be created and passed successfully. In my test specification, the following code is included: let component: Component; l ...

Angular's table data display feature is unfortunately lacking

Below is a simple HTML code snippet: <div class="dialogs"> <div id="wrapper" > <p>{{createTestingConstant()}}</p> <ng-container *ngFor="let one of contacts"> <p>{{one ...

Issue arises when integrating Angular 13 with ngrx and OAuth2: encountering difficulties in creating an effect

Currently, I'm following an example that uses an earlier version of Angular and ngrx. You can find the tutorial on NGRX Authentication in Angular with asp.net core here. This is what my Auth.action.ts file looks like: import { createAction, props } f ...

The filter predicate function is failing to produce a result and the following error occurs: Unable to access the 'data' property in MatTableDataSource within

There seems to be an issue with the function that is causing it to not work correctly the first time a letter is entered in the search bar. It returns nothing in the array initially, but works fine when letters are removed and typing continues. createFilt ...

Invoke a function in Playwright exclusively when the test title includes a specific @tag

After years of utilizing Selenium, SpecFlow, NUnit, and other testing tools, I have recently delved into Playwright with TS. My goal is to interact with the AzureDevOps API to mark tests as automated only if they contain a specific tag in the test title (e ...

Adding Rows Dynamically to Material Data Table in Angular 7

Is there a way to dynamically add data from a service into my table? I am receiving data from AuthenticationService dialog and attempted using this.dataSource.push(this.transaction);, but it did not work as expected. This is the code snippet where I trie ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

Utilizing PrimeNG TabView to automatically open a tab based on the URL

I have implemented PrimeNG's TabView component with three tabs - Home, Appointments, and Orders. In the Appointments and Orders tabs, there are lists of links that lead to individual appointment or order pages, which open as separate routes/pages out ...

What is the method to fetch the index and remove an element from an object in angular 8?

I've been attempting to remove an element from an object, but for some reason it's not getting deleted. The format of my object is as follows: {"UNDET":0,"HLDS":8,"NGS":2,"NGRT":1,"TotalCount":13,"NGX":1} What I'm looking to do now is del ...