Home > Back-end >  Having trouble switching a mat-icon back & forth between two icons
Having trouble switching a mat-icon back & forth between two icons

Time:10-02

I know I need to do a for loop or an if-statement of some sort, I've just been trying to put the pieces together for a few hours now with no luck. Any help would be greatly appreciated.

html

<button  type="button" mat-icon-button mat-mini-fab data-bs-target="#sidebar" 
          data-bs-toggle="collapse" (click)="changeIcon('arrow_back')"
          color="primary"><mat-icon>{{icon}}</mat-icon></button> <!--arrow_back-->

ts component

public icon = 'arrow_forward';
public changeIcon(newIcon: string){
this.icon = newIcon;

}

CodePudding user response:

If you want to toggle between the two icons, you can do something like this:

<button type="button" mat-icon-button mat-mini-fab data-bs-target="#sidebar" 
        data-bs-toggle="collapse" (click)="changeIcon()"
        color="primary"><mat-icon>{{icon}}</mat-icon></button> 
public icon = 'arrow_forward';
public changeIcon(): void {
   this.icon = this.icon === 'arrow_forward' ? 'arrow_back' : 'arrow_forward';
}

CodePudding user response:

Your code looks fine, it switches to arrow_back when you click on it. If you want to switch back to arrow_forward on the click it again you can simply toggle the values

<button type="button" mat-icon-button mat-mini-fab data-bs-target="#sidebar" 
              data-bs-toggle="collapse" (click)="changeIcon()"
              color="primary">
              <mat-icon> {{icon}} </mat-icon>
</button> 
 icon:string = 'arrow_forward';
 public changeIcon(): string {
    const temp = this.icon === 'arrow_forward'? 'arrow_back' : 'arrow_forward'
    this.icon = temp;
 }
  • Related