Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 change the style of a button onClick

Tags:

angular

I am having a lot of trouble trying to update the styling for a button on click.

First, here is the original markup:

<button class="btn btn-add" (click)="handleButtonClick(id)">
  Add<i class="fa fa-plus-circle"></i>
</button>

On clicking the button, I am trying to:

  1. Change the class from "btn btn-add" to "btn btn-remove"

  2. Change the <i class="fa fa-plus-circle"> to <i class="fa fa-minus-circle">

How can I do this the angular 2 way? Right now I just added a boolean and flip that, and show different templates based on the value. However, it seems there should be a way to handle this through some function right? In the documentation it says you can use strings delimited by a space for multiple classes, but I am not sure how to do that.

like image 696
user1354934 Avatar asked Sep 11 '16 18:09

user1354934


1 Answers

In your comment you stated, that you tried ngClass but had trouble with it:

The directive expects an object with the classname as key and an boolean expression as value. If the expression is true, the class is added, if not it will be removed.

For example your button has the class btn and should have either btn-add or btn-remove depending on a boolean value, than you probably do something like this:

<button class="btn" [ngClass]="{ 'btn-add': isAddButton, 'btn-remove': !isAddButton  }">
</button>

Hope this helps in your understanding of ngClass, then it won't be a problem to use it on your other usecases.

like image 174
malifa Avatar answered Oct 27 '22 11:10

malifa