Using ngClass with a Service property


#1

Hi… trying to use a service property to add a class to an element:

<button [ngClass]="{'active-button': this.nowPlayingService.playing}" (click)="playButton()" ion-button color="royal">
        <ion-icon class="control-icons" name="play"></ion-icon>
</button>

I have imported the service into the page .ts and the variable is updating properly, but the class is always on, even if the value of the ‘playing’ property is false. What am I doing wrong?

Thanks,
Marc
P.S. Happy Thanksgiving!


#2

I’m not sure is there way to use service in html directly, but if it possible - try to use it without this

<button [ngClass]="{'active-button': nowPlayingService.playing}" (click)="playButton()" ion-button color="royal">
        <ion-icon class="control-icons" name="play"></ion-icon>
</button>

If it don’t work, try to use method in your page class, that return this.nowPlayingService.playing

If it don’t work too, then create separate property in your page class playing and use it in html. Use ngOnChanges method in your page class, and check if property you need changed - change this.playing


#3

Hey – thanks for the tips. It turns out that my main problem was that I was improperly converting a string (“false”) to a boolean, which was causing all my booleans to evaluate to true. However, these tips helped me get some ngClass and ngIf stuff updating properly on model changes initiated by an asynchronous service, so thanks for laying out a few options. Definitely helpful. I ended up using a simple method that retrieves the class name on view update. (Note that using the service directly worked but wasn’t updating properly.)

Thanks,
Marc