Is ViewContainerRef.clear() responsible for deallocating component memory?

Is it necessary to set the property to null after calling ViewContainerRef.clear() when creating a component using ViewContainerRef and assigning an instance of it to the parent component responsible for child component creation in order to free up memory?

Answer №1

A common misconception is that assigning a parent component property to componentRef in Angular will automatically remove the component from memory.

In reality, Angular only destroys the component and removes its internal references to it. However, the reference to componentRef will still persist in your component property. To ensure proper memory cleanup, it's advisable to assign null to it. This way, the garbage collector can effectively clear memory.

Visual Example (add => clear => check)

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="addComponent()">Add component</button>
      <div #container></div>
      <button (click)="clear()">Clear</button>
      <button (click)="check()">Check</button>
    </div>
  `,
})
export class App {
  comp: ComponentRef<DynamicComponent>;

  constructor(
     private vcRef: ViewContainerRef, 
     private resolver: ComponentFactoryResolver) {}

  addComponent() {
    let factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.comp = this.vcRef.createComponent(factory);
  }

  clear() {
    this.vcRef.clear();
  }

  check() {
    alert(this.comp);
  }
}

For more information, refer to:

Answer №2

It seems that Angular triggers the ngOnDestroy() method of dynamically created components when their parent component is removed by the Router.

If you'd like to see a live example, check out this Plunker: https://plnkr.co/edit/rAX6745xZi6EvP8N78IL?p=preview

import {Component, NgModule,Injector, ComponentFactoryResolver, 
TemplateRef, ViewChild, ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Routes, RouterModule, Route} from '@angular/router';

@Component({
  selector: 'my-other',
  template: `<div>other</div>`
})
export class Other {}

// More code snippets and component definitions...

@NgModule({
  imports: [ BrowserModule, RouterModule.forRoot(routes ],
  declarations: [ App, MyComp, Parent, Other ],
  entryComponents: [MyComp],
  bootstrap: [ App ]
})
export class AppModule {}

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

Formatting code works seamlessly in vscode version 1.1.1 when using typescript 1.8.10

Currently running vscode version 1.1.1 with typescript. After upgrading to typescript 1.8.10, I've encountered issues with the 'format code' command not working, auto completion not functioning, and on the fly error checking and problem mat ...

What is the process for accessing a different view and its features on a separate screen using Angular portal?

In my angular project, I have multiple components. One component is being looped with an array using the following code: <body-chart *ngFor="..."></body-chart> Within the body-chart component : <div> <canvas id="canv ...

The Angular version update is experiencing issues within the Bash command prompt

https://i.stack.imgur.com/2ic0N.png I'm currently using version 6.0.8 of Angular, but when I try to add Angular/PWA to my project, I encounter an error. The command prompt shows my Angular CLI version as 6.0.8, however, in my bash command it displays ...

Managing asynchronous requests with RxJS for time-spaced dependent API calls

I am currently working on developing a code in Angular 11 to handle the following scenario: I have a list of files, and for each file, I need to make an API call (let's say api1) to retrieve a fileId from the response. Subsequently, I will use this f ...

Managing situations within the RxJS pipeline

I have an Observable called leadChanged$, which I can easily connect to the template using the async pipe. leadChanged$: Observable<LeadModel>; this.leadChanged$ = this.leadsDataService.leadChanged$.pipe( map((res) => ({ ... ...

Ways to display all properties of a component

I am seeking a way to retrieve all the component properties, including private and public ones, in Angular. My attempts so far include: ngOnInit() { console.log(this.constructor.prototype); } However, this code only displays properties with defined ...

Navigating between pages in Ionic 4 presents the opportunity to seamlessly transfer data using either the navCtrl or Router service

In the previous version of Ionic, Ionic 3, developers were able to use the second argument of the navController to easily pass data to the next page and retrieve it using the navParams service. This feature was quite convenient. Are there similar methods ...

Can Typescript restrict a value to only exist within a specified set of key names within the same object?

I am completely new to Typescript and I am fascinated by the way it can check types. One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are de ...

What is the best way to extract a specific element from JSON using Angular 2?

Handling a large and complex JSON object stored in a String variable can be tricky. Extracting specific elements, such as series_id and stadium, requires a clear understanding of how to navigate through the data. As a newcomer to angular2, the process mig ...

Arrange an array of objects by two characteristics, with the priority given to one over the other

I have a collection of objects that look like this: // items: [ {type: 'FRUIT', description: 'Apple'}, {type: 'VEGETABLE', description: 'Carrot'}, {type: 'FRUIT', description: 'Banana'}, ...

Loading compact Angular Modules in modules loaded lazily

After developing a module in Angular known as CustomCoreModule, it has gradually expanded over time and resulted in performance issues, leading to the app becoming non-modular and difficult to maintain. To address this issue, I have decided to split the l ...

Leveraging the TypeScript definitions for express-validator

I've been working on converting my code to TypeScript, but I'm running into issues with express-validator definitions. Here's a snippet of my code: ///<reference path='../../../d.ts/node.d.ts' /> ///<reference path=&apos ...

The TypeScript package encountered an unexpected token export

I have integrated a module from a private git repository. Package.json: "my-module": "git+https://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebeb98eaca7baacbbada5abbae0a1bca9">[email protected]</a> ...

Can we incorporate 'this' in the super() constructor?

While reviewing someone else's code, I came across the following snippet: class foo extends bar { constructor() { super(param1, param2, new certainObject(this, otherParams)); } } The issue with this code is that it generates an error ...

Encountering difficulties testing MatTable row population in Karma testing

Can someone please assist me in identifying the issues with my coding method? I attempted to replicate the techniques demonstrated in this tutorial on Harnesses Here is an Angular component that consists of a simple data table (MatTable) connected to a re ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

What is the best way to retrieve JSON data from a raw.github URL and save it into a variable?

Suppose there is a JSON file named data.json on Github. The raw view of the file can be accessed through a URL like this: https://raw.githubusercontent.com/data.json (Please note that this URL is fictional and not real). Assume that the URL contains JSON ...

Ionic 3 and Angular 6: Json Input Ended Abruptly

I've come across numerous discussions about the error I'm experiencing, but none of the solutions seem to apply to my situation. This morning, when I ran my code, I encountered the "Unexpected end of Json Input" error. Interestingly, I hadn' ...

Getting started with creating a dynamically changing table with just 2 initial rows is easier than you

My challenge is to dynamically create rows in a table, but I am unsure how to start the table with two rows on the onInit event. To get an idea of how the table operates, you can view it here: Visit stackblitz ...

fetching data with Contentful and GatsbyJS

I am currently working on fetching data from Contentful using GraphQL within a Gatsby application, and here is my approach: type AllContentfulBlogs = { allContentfulBlogs: { nodes: Array<{ title?: string | null | undefined, ...