Angular 2 change the style of a button onClick

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.


First of all, the behavior, visibility or the styling of an element should be driven by the state of your data and it should not alter itself.

Still, if you want to go like this, instead of using a boolean variable as a controller for this kind of functionality, you can pass the event to a function so you can get a reference to the element and it's classlist and manipulate it as you like.

You template should be like that:

<button class="btn" (click)="toggleClass($event)">

and add this in your class:

toggleClass(e) {
  const classList = e.target.classList;
  const classes = e.target.className;
  classes.includes('clicked') ? classList.remove('clicked') : classList.add('clicked');
}

To toggle the button's text too:

enter image description here

<button class="btn" [ngClass]="{'btn-add': !clicked, 'btn-remove': clicked}" (click)="clicked = !clicked">
    {{clicked ? 'Remove' : 'Add'}}
    <i class="fa" [ngClass]="{'fa-plus-circle': !clicked, 'fa-minus-circle': clicked}"></i>
</button>

Tags:

Angular