Ellone
Ellone

Reputation: 3898

Having angular [ngClass] refresh classes dynamically (based on data updated in a service)

I have a template with something like this:

<span [ngStyle]="{'color': s.isDetecting ? 'red' : 'green'}" class="right-icon">
    <i [ngClass]="s.isDetecting ? 'fas fa-eye' : 'fas fa-eye-slash'"></i>
    {{s.detectingStatus}}
</span>

In my component, I have basically this:

// ...
@Input() countSensor: PartyInfo = null;

s: DataInfo = null;

ngOnInit(): void {
  this.s = this.countSensor.data;
}

Note: countSensor is passed from parents to children and is updated every few seconds in a service.

Now, with this code, the [ngStyle] works properly, the color changes when it should, same for the {{s.detectingStatus}} string interpolation. However, the class doesn't seem to be updated with [ngClass]: The icon always stays the same.

How can I make my [ngClass] refresh the class and work dynamically as [ngStyle] does?


After some time researching here on SO and elsewhere, I've tried a few things :

Manually trigger the component change detection using the detectChanges() method from a ChangeDetectorRef passed to the constructor whenever my service updates my countSensor.

But this didn't change my behavior.

I also tried to use async in my template but I couldn't manage to do it since my s.isDetecting is not observable. Is there a simple way to make an observable bound to that variable? That might be a solution...

Upvotes: 0

Views: 1069

Answers (1)

Abhishek Kumar Pandey
Abhishek Kumar Pandey

Reputation: 449

Your value is coming as a Input, so watch it in ngOnchanges,

ngOnChanges(change:SimpleChange) {
  if(change.countSensor) {
    //put your logic here
  }
}

Upvotes: 0

Related Questions