Search code examples
angularloopsvariablesngfor

Angular variable in component loops


Immediately after I change the value of a property inside the class of a component I am using in a loop, it resets to the original value. This does not happen if I use the component alone, outside of any *ngFor.

For example, I have the following component:

export class CartProductComponent implements OnInit {
  loading = false;
    
  ...

  changeQuantity(change: number) {
    this.loading = true;
    ...
  }
}

that is used like this:

<app-cart-product *ngFor="let product of products" [product]="product"></app-cart-product>

Immediately after changeQuantity is called, the value resets to false.


Solution

  • Well, the problem you are experiencing is an expected behaviour, ngForOf will regenerate the view if it detects changes and the reference object its supplied with is not the same. Try using trackBy