Abdul khader
Abdul khader

Reputation: 67

How to active only one button at a time in ionic 2

I have group of four buttons

 <button round ion-button> David </button>

 <button round ion-button> Rocky</button>

 <button round ion-button> Chris</button>

 <button round ion-button> Johny</button>

I want to make the button active (change background color) only one button at a time in typescript. How to do.

Upvotes: 0

Views: 1131

Answers (1)

Gabriel Barreto
Gabriel Barreto

Reputation: 6421

You can use NgClass directive to conditionally assign the CSS class to your active button. To achieve this you'll need the CSS class and a property in your .ts to know what's the active button.

So your .TS will be:

export class YourPage {
  public active: string; // add this property
  constructor() { }

  // method to update the active property
  updateActive = name => this.active = name;
}

And then change your HTML:

<button round ion-button [ngClass]="'your-css-class': active === 'david'" (click)="updateActive('david')"> David </button>

<button round ion-button [ngClass]="'your-css-class': active === 'rocky'" (click)="updateActive('rocky')"> Rocky</button>

<button round ion-button [ngClass]="'your-css-class': active === 'chris'" (click)="updateActive('chris')"> Chris</button>

<button round ion-button [ngClass]="'your-css-class': active === 'johny'" (click)="updateActive('johny')"> Johny</button>

This should work, if you need a button to start active just asign a value to it in your active property. If your active button'll be managed in your .ts file just remove the click attribute. Here's the NgClass docs page if you need furter assistance.

Hope this helps.

UPDATE

Updated to use a method instead of directly assigning the value on the click, as op asked for.

Upvotes: 2

Related Questions