[Fixed] why is ngModel causing crash?

Issue

I use [(ngModel)] in a *ngFor-Loop. But this produces an endless-loop and a crash of the browser.

this is my html:

  <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 type of the 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 will be shown. But when I add the [(ngModel)] to the input, I get the problem. I have used item.key first for binding the ngModel, but this is also not working. After some googleing, I have tried it with the index, but this is also not working. I hope, someone can help me to solve it. Thank you.

Solution

I doubt it’s an endless loop but if your array is very large and especially if it’s updated often it could feel like an endless loop… you could try forcing angular to only update when you force it to.

In your ts file add

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

and then you can call this whenever your array gets populated or updated

this.cdr.detectChanges();

I would suggest this anyways for performance reason when dealing with arrays

Leave a Reply

(*) Required, Your email will not be published