Change button icon on click


#1

Hello all,

can someone tell me why the following code does not work?:

Im trying to change the buttons icon on click event by using a local variable (#minimizeIcon) in my template.
But if i click the button nothing happens.

If i do this with data binding ( [name]=“myVariable”) and change the variable from inside the component class it works. But i thought it should work with a local template variable too.

 <button ion-fab mini clear (click)="minimizeIcon.name = 'arrow-dropup'">

       <ion-icon #minimizeIcon name="arrow-dropdown"></ion-icon>

  </button>

As im still new to ionic/typescript, i hope someone can explain why this dont works :slight_smile:

Thank you

Kind regards.


#2

I’m not sure I can explain why this doesn’t work, but perhaps I can suggest what does.

<button (click)="toggleZipped()">
  <ion-icon [name]="zipped ? 'arrow-dropdown' : 'arrow-dropup'"></ion-icon>
</button>

zipped: boolean = true;
toggleZipped(): void {
  this.zipped = !this.zipped;
}

This approach also allows you to easily do the rest of the zippy with something like:

<div *ngIf="!zipped"><ng-content></ng-content></div>

#3

Simply because you are missing data binding, how else do you think the changed value would be reflected back?

See, your code is fine and working. If you log the minimizeIcon.name after the click event, you’ll see the changed value. But, as it’s not bound to anything it’ll not automatically get reflected in your view. What you need to do is this:

Declare a variable in your component, for example:

mIName: string = "arrow-dropdown";

… and in your template markup do this:

<button ion-fab mini clear (click)="mIName = 'arrow-dropup'">
   <ion-icon #minimizeIcon [name]="mIName"></ion-icon>
</button>

Now your code will do what you were looking for in the first place.