Angular 2 change onClick button style

I have a lot of problems trying to update the style for the button when I click.

Firstly, here is the original markup:

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

When I click the button, I try:

  • Change class from "btn btn-add"to"btn btn-remove"

  • Change <i class="fa fa-plus-circle">to<i class="fa fa-minus-circle">

How can i do this angular 2? Right now, I just added a boolean and a flip, and I will show different patterns based on value. However, there seems to be a way to handle this through some features? The documentation says that you can use strings limited to spaces for multiple classes, but I'm not sure how to do this.

+4
source share
3 answers

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

. , , .

, btn btn-add, btn-remove , , , - :

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

, ngClass, .

+12

:

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

To switch the button text:

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>
+2
source

Source: https://habr.com/ru/post/1654287/


All Articles