Recreating components with every change check, Angular 2's *ngFor feature constantly updates

Within my code, I am utilizing two nested *ngFor loops. The first loop iterates through libraries, while the second one iterates through all items within each library, where a specific Angular component is dedicated to each item.

The issue arises when these item components are recreated with every change check in Angular. This was discovered by inserting a logger into the ngOnInit() handler of the item component. Each time any modification is made on the page, the logger is triggered, resulting in a reset of the component's state and loss of any changes. As a result, attempts to modify the component's state become ineffective, essentially breaking the functionality of the application.

Although I attempted to resolve this by implementing trackBy: trackByFn, it did not alleviate the problem.

Container:

<div *ngFor="let lib of libraries">
  <div *ngIf="lib.components.length" class="groupContainer" [class.closed]="!libraryIsOpened(lib)">
    <div class="title flex flex-row" (click)="toggleLibrary(lib)">
      <p>{{ lib.name === '__none' ? 'No Library' : lib.name }} ({{ lib.components.length }})</p>
      <div class="flex flex-grow"></div>
      <i class="mdi mdi-chevron-up iconClose"></i>
      <i class="mdi mdi-chevron-down iconOpen"></i>
    </div>
    <div class="content">
      <app-component-list-item *ngFor="let c of components; trackBy: trackByFn"
                     class="flex"
                     [component]="c">
      </app-component-list-item>
    </div>
  </div>
</div>

List Item:

import ...


@Component({
  selector: 'app-component-list-item',
  templateUrl: './component-list-item.component.html',
  styleUrls: ['./component-list-item.component.scss']
})
export class ComponentListItemComponent implements OnInit {

  @Input() component: PipelineComponent

  constructor(private el: ElementRef, private nodeCreator: NodeCreationService) {
  }

  ngOnInit() {
    console.log('init')
  }

  trackByFn(index, item) {
    return this.component.componentID
  }
}

Answer №1

It's difficult to pinpoint the exact reason without reviewing more of your code. My hunch is that the issue may be related to the dynamic nature of the libraries variable (are you perhaps using Redux? In that case, any modifications to elements or properties within libraries would trigger a change in the top-level list). As a result, Angular's change detection mechanism interprets these modifications as changes to the entire array, causing it to recreate new components for each element. To mitigate this behavior, consider storing a mutable copy of libraries in the parent component and modifying it directly. By doing so, Angular will only detect individual element changes instead of perceiving updates to the whole array.

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

In Typescript 2.2, when using Express, the request and response objects are implicitly

I'm facing some challenges when it comes to incorporating types into my node/express project. Currently, I am using TypeScript 2.2 and express 4.x with the following npm installation for types: npm install --save-dev @types/express import * as expr ...

The element of type 'any[]' cannot be assigned to type '[id: string]'

My goal is to develop a versatile API structure, where the properties are functions that return Promises. export type API = { [key: string]: <Params extends any[], Response>(...params: Params) => Promise<Response>, } export interface User ...

What is the reason behind the return type of 'MyType | undefined' for Array<MyType>.find(...) method?

Currently, I am in the process of developing an Angular application using TypeScript. As part of this project, I have defined several classes along with corresponding interfaces that align perfectly with their respective properties: Map: export class Map ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

The deployment of the remix is unsuccessful in Vercel, even though it functions perfectly during development. The error message states that 'AbortController' is not

I'm new to React and could use some assistance with a deployment issue on Vercel. Any ideas on why this is failing? I haven't explicitly used AbortController anywhere, so I'm suspecting it might be related to one of the installed packages? ...

Issue: The function (0, react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not recognized as a valid function or its output is not iterable

I found a great example of using useActionState at this source. Currently, I am implementing it in my project with Next.js and TypeScript. app/page.tsx: "use client"; import { useActionState } from "react"; import { createUser } from ...

How can I use TypeScript to copy data from the clipboard with a button click?

One of the functionalities I have implemented is copying data to the clipboard with a button press. However, I am now looking to achieve the same behavior for pasting data from the clipboard. Currently, the paste event only works when interacting with an i ...

Is app.component.ts necessary in an Angular 2 project?

Currently diving into Angular 2 and have a burning question on my mind. Do I really need the app.component.ts file in my project? Each of my folders has its own component and template, so I'm debating if the main component is necessary or if I can rem ...

Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship: Departament: @Entity('Departament') export default class Departament { @PrimaryGeneratedColumn() id: string; @Column() departament_name: string; @OneToOne(type ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

Uh-oh! You can't configure Next.js using 'next.config.ts'. You'll need to switch it out for 'next.config.js'

I've encountered an issue while working on my TypeScript project with Next.js. Initially, I named my config file as next.config.js, but it resulted in a warning in the tsconfig.json file stating "next.config.ts not found," leading to a warning sign on ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

The Angular frontend application with proxy configuration is sending requests to the incorrect backend URL

My application is using Angular 11.0.6 as the front end, deployed on IIS and configured for mywebsite.com (port 80). The backend consists of a dotnet core web API deployed on IIS and configured for my.server.ip.address:190. Both the front end and back end ...

Leveraging LESS in an Angular2 component

Currently, I am attempting to integrate LESS with angular2. To do so, I have imported the less.js file in my index.html and I am using the following command within the component: less.modifyVars({ '@currentTheme-bar': '@quot ...

I am having trouble with Angular not redirecting to the correct page and I'm not sure how to troubleshoot this issue

After creating a component named detail that is supposed to be associated with a button, I encountered an issue where it doesn't route me to the desired location. Strangely, no error messages are displayed, leaving me puzzled about how to solve this p ...

Unable to retrieve the headers from the error response

When working with Angular 6, I encountered an issue where I couldn't retrieve the headers from an HTTP error response. Specifically, when the server responded with a status code of 401, additional headers were included in the error response. What is t ...

Combining vue with deno and vscode: A guide to seamless development integration

How can I set up Visual Studio Code for a Vue project using Deno? Important note - the issues mentioned here only pertain to highlighting in VSCode, as the builds, development, and scripts are functioning correctly! Deno + Vue is an appealing choice! You ...