如何在 ionic 2 中一次只激活一个按钮
How to active only one button at a time in ionic 2
我有一组四个按钮
<button round ion-button> David </button>
<button round ion-button> Rocky</button>
<button round ion-button> Chris</button>
<button round ion-button> Johny</button>
我想在打字稿中一次只激活一个按钮(更改背景颜色)。怎么做。
您可以使用 NgClass
指令有条件地将 CSS class 分配给您的活动按钮。为此,您需要在 .ts 中使用 CSS class 和 属性 来了解什么是活动按钮。
因此您的 .TS 将是:
export class YourPage {
public active: string; // add this property
constructor() { }
// method to update the active property
updateActive = name => this.active = name;
}
然后改变你的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>
这应该有效,如果您需要一个按钮来启动活动,只需在您的 active
属性 中为其分配一个值即可。如果您的活动按钮将在您的 .ts 文件中进行管理,只需删除 click 属性。如果您需要进一步的帮助,请点击这里 NgClass docs page。
希望这对您有所帮助。
更新
已更新为使用一种方法,而不是像 op 要求的那样直接在点击时分配值。
我有一组四个按钮
<button round ion-button> David </button>
<button round ion-button> Rocky</button>
<button round ion-button> Chris</button>
<button round ion-button> Johny</button>
我想在打字稿中一次只激活一个按钮(更改背景颜色)。怎么做。
您可以使用 NgClass
指令有条件地将 CSS class 分配给您的活动按钮。为此,您需要在 .ts 中使用 CSS class 和 属性 来了解什么是活动按钮。
因此您的 .TS 将是:
export class YourPage {
public active: string; // add this property
constructor() { }
// method to update the active property
updateActive = name => this.active = name;
}
然后改变你的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>
这应该有效,如果您需要一个按钮来启动活动,只需在您的 active
属性 中为其分配一个值即可。如果您的活动按钮将在您的 .ts 文件中进行管理,只需删除 click 属性。如果您需要进一步的帮助,请点击这里 NgClass docs page。
希望这对您有所帮助。
更新
已更新为使用一种方法,而不是像 op 要求的那样直接在点击时分配值。