0

I am trying to update UI automatically, avoiding jQuery. I just want to update a css of a button after a click happened.

Should it be done in html with inline javascript code or typescript component?

Right now I am evaluating the latter, handling CSS in typescript as follows.

The component which changes its alreadyLiked property:

sendLike(recipientId: number) {
  this.userService.sendLike(fromUserId, this.user.id).subscribe(data => {
      this.alertifyService.success('You have liked ' + this.user.name);

     // any way to update UI without this trash?
     const btnLikeMe = <HTMLInputElement> document.getElementById('btnLikeMe');
     btnLikeMe.classList.remove('btn-primary');
     btnLikeMe.classList.add('btn-success');
     btnLikeMe.classList.add('active');
     btnLikeMe.disabled = true;

   }, error => {
        this.alertifyService.error(error);
   });
}

After alreadyLiked is changed, I would like to update btnLikeMe css automatically in HTML:

<button id="btnLikeMe" class="btn" (click)="sendLike(user.id)"
[disabled]="alreadyLiked"
[ngClass]="alreadyLiked ? 'btn-success active' : 'btn-primary'"
title="{{alreadyLiked?'You already liked me. Thank you' : 'Like me now!'}}">
Like
</button>

It is working but it seems to be a bad approach. I am using "@angular/core": "^5.2.0"

Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161

1 Answers1

0

You don`t need JQuery for this. NgClass is the right way.

NgClass adds and removes CSS classes on an HTML element.

In some point if you want do to more complex things you can call functions...[ngClass]="getClass()" Then you can debugging, but you can`t do this in HTML. When you have to touch the DOM, you should use Renderer2.

Angi90
  • 1
  • 4
  • [ngstyle-vs-renderer2](https://stackoverflow.com/questions/50193146/ngstyle-vs-renderer2-what-should-i-use) – Angi90 Jul 28 '18 at 07:01