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

Employing both Angular 1 and Angular 2 in conjunction

As a newcomer to angular, this is my first experience. My ultimate goal is to incorporate the following component into Angular 2: While I have some knowledge of JavaScript, I am attempting to integrate an Angular 1 library into an Angular 2 project. Aft ...

Module not found

Hey everyone, I recently updated my project to node version v14.18.0, but now I'm encountering a "module not found" issue (see screenshot below). Any suggestions on how to resolve this? https://i.stack.imgur.com/k0u82.png ...

Applying ngModel within ngFor can overwrite the current value

Welcome to my HTML file! <form [formGroup]='itemUpdateForm'> <div class="row"> <mat-form-field class="col-sm-8"> <mat-label>Restaurant Name:</mat-label> <i ...

Is it possible for the *ngIf directive to stop unauthorized users from accessing my admin page through their browsers?

When the *ngIf directive is set to false, a certain element or component will not be included in the DOM. For example, let's say there is a component that displays admin tools and should only be accessible to authorized users (administrators). Will se ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...

The TypeScript compiler encounters difficulties in locating type definitions when utilizing an inherited tsconfig file

There seems to be an issue with the functionality of tsconfig.json inheritance, specifically regarding the proper inheritance of the "typeRoots" setting. http://www.typescriptlang.org/docs/handbook/tsconfig-json.html (folder structure provided below) we ...

Encounter an error during testing with jest where the issue arises from converting circular structure to JSON in moment.js on a specific line

While working with Angular and Jest, I encountered an error when incorporating moment.js into my code. Below is the import statement in my component: import * as moment from "moment"; The line where the error occurs: const date = moment(new Dat ...

Show image using Typescript model in Angular application

In my Angular (v8) project, I have a profile page where I typically display the user's photo using the following method: <img class="profile-user-img" src="./DemoController/GetPhoto?Id={{rec.Id}}" /> However, I am considering an alternative ap ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Encountering a 404 error while attempting to test a contact form on a Next.js website using a local server

Trying to test a contact form in Next.js where the data is logged but not sent to the API due to an error. "POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)" Troubleshooting to identify the issue. [directory setup] ...

Enhancing Type Safety in Typescript through Key/Property Type Guards

Is it possible to create a typeguard that can confirm the existence (or specific type) of a property in an object? For example: Consider an interface Foo: interface Foo { bar: string; baz: number; buzz?: string; } An object of type Foo may ...

Testing the open dialog with a unit test case

I encountered an issue while writing a unit test case for the open dialog feature in Angular 7. A TypeError is being thrown: "Cannot read property 'debugElement' of undefined." I am seeking assistance from anyone who can help me troubleshoot this ...

When running the command ng build --prod, it seems that the module for class X cannot be determined. To resolve this issue, make sure to include

I'm encountering an issue while trying to develop my Angular 5 application. The error message reads: Cannot determine the module for class ThreadListTabsComponent in /home/brightwater/Differ/src/app/thread-lists/thread-lists.component.ts! Add T ...

Countdown component in Ant Design failing to display correct date

I’m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Error encountered when implementing Angular Model Class within an array structure

In the current project, I have developed a class and am attempting to utilize the constructor format for certain content within the project. Here is my Angular class - import { Languages } from './temp-languages.enum'; export class Snippet { ...

Issue with Promise not resolving in Node when using Edge

As I explore the best way to utilize my C# dlls with Edgejs for Node, I encountered a situation where one proxy function in Node appears like this (a class method in Typescript): readSettings(args: ReadSettingsParams) : Promise<response> { let $ ...

Error: TypeScript React SFC encountering issues with children props typing

I am currently working with a stateless functional component that is defined as follows: import { SFC } from "react"; type ProfileTabContentProps = { selected: boolean; }; const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, child ...

Do Angular 2 component getters get reevaluated with each update?

What advantages do getters offer compared to attributes initialized using ngOnInit? ...

Troubleshooting Component Sharing in Ionic 4 with Angular 7

I'm attempting a common task with Angular framework - reusing the same HeaderComponent component in multiple instances through a shared module. This is how my shared.module.ts looks: import { CommonModule } from '@angular/common'; import { ...

The term "define" is not recognized when constructing a Next.js application

Currently, I am working with Next version 10.0.1 and React 17.0.2. While attempting to build my Next app, I encountered the following error: ReferenceError: define is not defined at Object.<anonymous> (/Users/username/Desktop/project/node_module ...