Search code examples
angulartoggleglyphicons

change glyph-icon on click on the button in angular 2


I want that when I click this button, the 'glyphicon-plus' change to 'glyphicon-minus' and when i again click, it will again 'glyphicon-plus'. I want It should be Toggelable. I dont want it in css or jquery. app.component.html :

<button data-toggle="collapse" 
        [attr.data-target]="'#demo' + RowIndex">
        <span class="glyphicon glyphicon-plus"></span>
</button>

Solution

  • In your template, use a sign binding and a click event binding as follows:

    <button data-toggle="collapse" 
            (click)="toggleSign()"
            [attr.data-target]="'#demo' + RowIndex">
            <span class="glyphicon glyphicon-{{sign}}"></span>
    </button>
    

    In your component class, change the sign property on each click.

    export class MyComponent {
       ....
       sign = 'plus';  // or minus if you want that first
    
       toggleSign() {
         if(this.sign == 'plus') {
           sign = 'minus';
         } else {
           sign = 'plus';
         }
       }
      ......
    
     }
    

    Always think of things this way in Angular - my view as a reflection of the state of my components. So if i want to change things visually, using the binding system to bind the variable parts of my view to properties of my components and just change the component properties to reflect the view that i want.