Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngClass/ngIf not rerendering on changes

I'm working on an Angular project where I need to have one class or another depending on a variable (and they have to change live, without refreshing).

I tried using *ngIf/else and [ngClass]and they do work but they do not re-render. They only work when I refresh the website

Using *ngIf/else:

<i
 *ngIf="favSongs.includes(track.id); else plus"
 (click)="setToFav(track.id)"
 class="fa fa-check"
></i>
<ng-template #plus>
  <i (click)="setToFav(track.id)" class="fa fa-plus"></i>
</ng-template>

Using [ngClass]:

<i
  (click)="setToFav(track.id)"
  [ngClass]="{'fa fa-check': favSongs.includes(track.id), 
  'fa fa-plus': !favSongs.includes(track.id)}"
></i>

As said before, it does work but only when you refresh. I'm looking for something like React, when you update the class the component get re-rendered.

like image 564
Mr. Moretto Avatar asked Oct 28 '25 09:10

Mr. Moretto


1 Answers

Change detection only fires when the value of a binding has changed. The value for primitives is their value, and for objects its the value of their reference.

Adding a track to an array of tracks will mutate the binded object, but not change its reference, and not trigger change detection.

This is one reason for using immutable objects.

In setToFav you could do faveSongs = faveSongs.push(track.id).slice(); or so.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!