首页 > 解决方案 > 当变量更改值时,Ionic 4 离子按钮不更新 ngStyle

问题描述

我在 Ionic 4 项目中设置了一个页面,这样当单击按钮时,变量会更改值并且 ngStyle 意味着要更新。在我的例子中,我们有两个按钮,“朋友”和“家人”,当一个被选中时,我想要背景为绿色,另一个是透明的。在初始设置中,朋友按钮是绿色的,家庭按钮是透明的。但是,当我单击家庭按钮时,变量将值更改为“家庭”,正如我在 console.log 输出中看到的那样,但此更改并未按预期反映在按钮中。发生的情况是“家庭”按钮变为绿色,但“朋友”按钮保持绿色。从这里开始,任何更多的点击都不会改变任何东西。

// .ts file

// setting initial variable
selectedCat = "friends";

// functions to update on button click
showFriends() {
    this.selectedCat = "friends";
    console.log('This is this.selectedCat showFriends', this.selectedCat);
  }

  showFamilies() {
    this.selectedCat = "families";
    console.log('This is this.selectedCat showFamilies', this.selectedCat);
  }
<ion-buttons slot="end">
        
<ion-button expand="block" fill="outline" [ngStyle]="selectedCat == 'friends' ? {'background-color': '#90EE90'} : {'background-color':'clear'}" [color]="dark" (click)="showFriends()" item-left>
              Friends
</ion-button>

<ion-button expand="block" fill="outline" [ngStyle]="selectedCat == 'families' ? {'background-color': '#90EE90'} : {'background-color':'clear'}"  [color]="dark" (click)="showFamilies()" item-left>
              Families
</ion-button>
          
</ion-buttons>

标签: angularionic4

解决方案


我很确定'clear'不是css的有效颜色。您可以尝试将其更改为此处显示的有效 html 颜色名称:https ://www.w3schools.com/tags/ref_colornames.asp吗?

您还可以使用“未设置”来“删除”背景颜色:

<ion-button expand="block" fill="outline" [ngStyle]="selectedCat == 'friends' ? {'background-color': '#90EE90'} : {'background-color':'unset'}" [color]="dark" (click)="showFriends()" item-left>
              Friends
</ion-button>

推荐阅读