On specific button click add a class in ionic 3

Issue

I have a situation where i have multiple records and i used in that *ngFor loop , so per record there is one button And I am trying to do is onclick change background of button so that it looks alike it is clicked

<div class="main" *ngFor="let data of fetched_info; let i=index">
    <ion-grid no-padding no-margin>
        <ion-row no-padding no-margin class="row">
            <ion-col col-4 no-padding no-margin> 
                <button ion-button small icon-start color="secondary"
outline (click)="shortlist($event,data[i].username)" class="">
                    <ion-icon ios="ios-star-outline" md="md-star-outline"></ion-icon>
                    Shortlist
                </button>
            </ion-col>

        </ion-row>
    </ion-grid>
</div>

onclick of shortlist() function i want to make it happen

Solution

you can try like this

HTML

<div class="main" *ngFor="let data of fetched_info; let i=index">
 <ion-grid no-padding no-margin>
     <ion-row no-padding no-margin [ngClass]="backgroundColorFlag[i] == true ? 'backgroundColorClass' : 'backgroundColorNormalClass' " class="row">
       <ion-col col-4 no-padding no-margin> 
         <button ion-button small icon-start color="secondary"
           outline (click)="shortlist($event,data[i].username, i)" class="">
           <ion-icon ios="ios-star-outline" md="md-star-outline"></ion-icon>
            Shortlist
         </button>
       </ion-col>
     </ion-row>
 </ion-grid>
</div>

TS

    backgroundColorFlag: any[] = [];
    shortlist(data, i) {
      this.backgroundColorFlag[i] != this.backgroundColorFlag;
    }
    functionWhichHavefetched_info() {
     for (let i = 0; i < fetched_info.length; i++) {
           this.backgroundColorFlag[i] = false // default we are setting value false and on click we set this flag value true
      }
    }

you need to create a class like this backgroundColorClass and backgroundColorNormalClass and add or remove class by using a flag backgroundColorFlag i hope it helps you out

Answered By – Yash Rami

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published