What could be the reason for the crash caused by ngModel?

The usage of [(ngModel)] within a *ngFor-Loop is causing an endless loop and crashing the browser.

This is how my HTML looks:

  <div class="container">
    <div class="row" *ngFor="let item of controlSystemTargetViewModel.values; let index = index;">
      <div class="col" style="vertical-align: middle; font-weight: bold; margin-bottom: 0.5em;" >{{controlSystemTargetViewModel.values[index].assemblyType}}</div>
      <div class="col">
        <input type="text" name=sg{{index}} class="form-control" style="text-align: center; margin-bottom: 0.5em;" [(ngModel)]="controlSystemTargetViewModel.values[index].key"  mdbInput>
      </div>
    </div>
  </div>      

This is the data type for elements in values:

import { ControlSystemTargetValueDto } from "src/app/api/models";

export class ControlSystemTargetValueViewModel {
    constructor(private dto: ControlSystemTargetValueDto) {
    }

    get assemblyType() : string {
        return this.dto.assemblyType; 
    }

    get key(): string {
        return this.dto.key;
    }

    set key(val : string) {
        this.dto.key = val; 
    }
}

controlSystemTargetViewModel.values[index].assemblyType
gets displayed correctly. However, introducing [(ngModel)] to the input field causes the issue. I initially tried using item.key for binding with ngModel, but that didn't work either. After some research online, I attempted to use the index, which also failed. Any assistance in resolving this problem would be highly appreciated. Thank you.

Answer №1

It's unlikely to be an infinite loop, but if you're working with a large array that is frequently updated, it could create a similar effect. One way to potentially address this issue is by controlling when Angular updates.

In your typescript file, include the following:

@Component({
    ...
    changeDetection: ChangeDetectionStrategy.OnPush,
    ...
})
constructor(... private cdr: ChangeDetectorRef) {}

Then, call this method whenever your array changes:

this.cdr.detectChanges();

Regardless, using this approach can improve performance when managing arrays.

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 steps should I take to update the Angular CLI version?

I am currently struggling with the installation of Angular CLI version 15.2.8, despite my attempts to upgrade. Currently, I have the following version of Angular: https://i.stack.imgur.com/m477e.png In an effort to change the version, I have been runnin ...

What is the best way to ensure the website theme remains consistent after a refresh in React?

I am currently enhancing a weather forecast website by incorporating a theme toggler feature. The functionality has been successfully implemented, but I am facing an issue where the selected theme does not persist after reloading the page. Can someone he ...

Adding URL path in Angular 7's .ts file

I currently have the following code in my component's HTML file: <button mat-flat-button class="mat-flat-button mat-accent ng-star-inserted" color="accent" (click)="playVideo(video)"> <mat-icon [svgIcon]="video.type === 'external' ...

Creating an Angular template using the Teams Toolkit within Visual Studio Code

I'm looking to create a basic step-by-step form on Microsoft Teams using my existing Angular application. However, I've noticed that there are only React templates available in Visual Studio Code for building tabs in Teams. Do I have to use these ...

What is the best way to implement react-password-checklist with zod?

I've been trying to utilize the react-password-checklist library to inform users if their password complies with the rules set in zod's schemaUser. However, I'm facing challenges in implementing this feature successfully. Note: I am using zo ...

Adding *ngIf dynamically within a directive allows for conditional rendering based on certain parameters or

Is there a way to dynamically include an *ngIf on an element that is decorated with an attribute directive? I decided to test this with a simple experiment: @Directive({ selector: '[lhUserHasRights]' }) export class UserHasRightsDirective i ...

Get the latest B2B department for the client within Spartacus

How can I display the current B2B Unit name in the header for the customer? I have been exploring ways to retrieve the B2B Unit for the current customer and found that there is a payload available for the /current? endpoint that loads on the initial page ...

Preventing users from entering past dates in Angular 6 - A step-by-step guide

Here is my current code snippet: ngOnInit() { let now = new Date(); this.date = formatDate(now, "dd/mm/yyyy",'en-US'); console.log("dateFormat :",this.date); } This is the html part of my code: <input type="date" [min]={{da ...

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

Directly retrieve the result from http service (observable) without the need to return Observable from the function

Is there a way to directly return a result from the service without returning Observable and then using then clause? I've experimented with methods like pipe, of, take, toPromise, map, async-await, but none of them seem to return the result on a servi ...

Leveraging pipes in Angular 2 within the (click) event handler

I have a question that may seem simple, but I'm struggling to figure out how to use a pipe within an event like (click). Here is an example of what I'm trying to do: <button (click)="quizAnswers(answer?.texte | translate | async)"></but ...

Creating a blank webpage after including a component tag for an Angular form

I encountered an issue while developing an Angular form. It seems that using the app-name-editor tag causes my entire HTML page to go blank, and the form does not display. However, removing the tag restores the webpage's functionality. This leads me t ...

Unable to connect to localhost nodejs server from Windows browser when using WSL2

My computer runs on Windows 10 and has the Linux (Ubuntu-20.04) subsystem using WSL2. I've successfully initiated a frontend project (vue project) and running npm run serve works as expected with the application running on localhost:8080. However, whe ...

Exporting the interface for the state of the redux store

After setting up a redux module, I have organized the following files: //state.tsx export default interface State { readonly user: any; readonly isLoggedIn: boolean; } //types.tsx export default { REQUEST: 'authentication/REQUEST', SUC ...

Using the parameter of type 'never' is necessary as per the TypeScript error message, which states that the argument of type 'string' cannot be assigned to it. This error persists even when

const index = selectedActivities.value.indexOf(activity_id); I encountered a TypeScript error saying 'Argument of type 'string' is not assignable to parameter of type 'never'. How can I fix this issue? ...

Leveraging React and TypeScript's capabilities to pass around arguments efficiently

As I integrate TypeScript into my application, I find myself at a juncture where I need to specify the following: { id, label, type, styles, ...props } Incorporating this structure into a component like the one below: const TestComponent = ({ id, label, t ...

Unable to display content within the router-outlet

I'm currently attempting to dynamically change the router outlet based on authentication status. My code looks something like this: <div *ngIf="isLoggedIn" class="layout-wrapper layout-2" [ngClass]="{'layout-loading&ap ...

Step-by-step guide for integrating Google Closure Library with Angular 10

Is there a way to integrate the Google Closure Library into an Angular 10 project? I attempted to install it using npm install google-closure-library, but encountered an error stating Could not find a declaration file for module 'google-closure-librar ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

Incorporating Vaadin components into an Angular2-seed project

Hi there, I've been encountering an issue while trying to integrate Vaadin elements into my Angular2 seed project. The Vaadin team has recommended that I upgrade the systemjs.config.js file by specifying the path names for Vaadin elements like this: ...