angular - 我有两个按钮,我需要在 Ionic 中更改两个按钮中的任何一个的颜色

标签 angular typescript ionic2 ionic3

我的 HTML 文件中有两个按钮

<div>
  <button  ion-button outline (click)="selectUnit(200)">200gms</button>
  <button  ion-button outline (click)="selectUnit(400)">400gms</button>
</div>

所以当用户点击 200gms 时,我想突出显示它的颜色,如果他点击 400,我希望它突出显示 400。

我在网上进行了大量研究并找到了解决方案,例如 -

<button [attr.newColor]="addAttribute ? '' : null">Test</button>

但是这里发生的是,该属性将更改为 true,并突出显示两个按钮。

我只想突出显示按下的按钮并保持突出显示,直到按下另一个按钮。

最佳答案

您可以使用该组件的属性来保留所选值,然后使用按钮color 属性根据当前所选值更改它。

请看这个 Working stackblitz demo .

enter image description here

组件:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  public selected: number;

  constructor(public navCtrl: NavController) {}

  public selectUnit(unit: number): void {
    this.selected = unit;
  }

}

查看:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Ionic!</h2>

  <p>Selected: {{ selected }}</p> 

  <div>
    <button [color]="selected === 200 ? 'secondary' : 'primary'" ion-button outline (click)="selectUnit(200)">200gms</button>
    <button [color]="selected === 400 ? 'secondary' : 'primary'" ion-button outline (click)="selectUnit(400)">400gms</button>
  </div>
</ion-content

请注意,我使用 [color]="selected === 200 ? 'secondary' : 'primary'" 根据 的值为每个按钮选择正确的颜色>selected 属性。

关于angular - 我有两个按钮,我需要在 Ionic 中更改两个按钮中的任何一个的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585601/

相关文章:

php - 如何使用 Angular http.delete 和 PHP 后端从表中删除记录?

javascript - 将初始值设置为 Angular 表单组以进行测试

Angular 4 错误类型错误 : Cannot read property 'dirty' of undefined

javascript - TypeScript/Angular $q 立即解决延迟不起作用

javascript - 异常:在 ionic 2 应用程序中使用 facebook 登录后未捕获( promise )

Angular - 找不到管道 'keyvalue'

typescript - 类型中缺少 Object.entries 属性 'length'

TypeScript const 和 const with as const

ionic2 - Ionic 2 - 幻灯片如何更改分页进度颜色?

javascript - 在图像加载时显示加载图标