【问题标题】:How to change the color of only one button?如何只更改一个按钮的颜色?
【发布时间】:2018-09-15 00:08:11
【问题描述】:

我有问题。我用 HTML 中的按钮制作了一个循环。所以现在我希望他们在我按下按钮时改变颜色。但我有一个问题,他们都改变了颜色。但我只想更改按下按钮的颜色。

HTML

 <ion-item *ngFor="let friend of friendsList">
      <ion-avatar item-start>
        <img src={{friend.img}}>
      </ion-avatar>
      <button ion-button color="rank" class="avat"> </button>
      <h2>{{friend.name}}</h2>
      <p>{{friend.status}}</p>
      <button (click)="toggleNamedColor()" ion-button round color="rank" [color]="ionicNamedColor" item-end>+Add</button>

    </ion-item>

  </ion-list> 

TS

public ionicNamedColor: string = 'rank';

public toggleNamedColor(): void {
      if(this.ionicNamedColor === 'rank') { 
        this.ionicNamedColor = 'primary'
      } else {
        this.ionicNamedColor = 'rank'
      }
    }

【问题讨论】:

  • 能否也添加循环代码?无论如何,您基本上可以遍历循环中的每个按钮并直接设置它们的颜色而不是使用变量。
  • 你可以像&lt;ion-item *ngFor="let friend of friendsList"&gt; &lt;button (click)="toggleNamedColor(friend)" ion-button round color="rank" [color]="friend.ionicNamedColor" item-end&gt;+Add&lt;/button&gt; &lt;/ion-item&gt;一样使用它,然后在ts中更改friend.ionicNamedColor
  • @XYZ 你能帮我解决 TS 部分的问题吗?我不知道要对friend.ionicNamedColor 进行哪些更改。因为当我更改this.ionicNamedColor时,出现错误(点前的朋友)是红色下划线

标签: javascript html typescript ionic-framework


【解决方案1】:

您可以像这个例子一样尝试通过向对象添加颜色属性并在点击时更改该对象的颜色属性

 <ion-list> 
    <ion-item *ngFor="let friend of friendsList">
          <ion-avatar item-start>
            <img src={{friend.img}}>
          </ion-avatar>
          <button ion-button color="rank" class="avat"> </button>
          <h2>{{friend.name}}</h2>
          <p>{{friend.status}}</p>
          <button (click)="toggleNamedColor(friend)" ion-button round color="rank" [color]="friend.ionicNamedColor" item-end>+Add</button>

        </ion-item>

      </ion-list>

在ts中

public toggleNamedColor(friend): void {
      if(friend.ionicNamedColor === 'rank') { 
        friend.ionicNamedColor = 'primary'
      } else {
        friend.ionicNamedColor = 'rank'
      }
  }

【讨论】:

    【解决方案2】:

    请尝试使用 ngFor 中的索引

    HTML

    <ion-item *ngFor="let friend of friendsList;let i = index">
          <ion-avatar item-start>
            <img src={{friend.img}}>
          </ion-avatar>
          <button ion-button color="rank" class="avat"> </button>
          <h2>{{friend.name}}</h2>
          <p>{{friend.status}}</p>
          <button (click)="curIndex = i" ion-button round [color]="curIndex == i ? 'rank' : 'primary'" item-end>+Add</button>
    
        </ion-item>
    

    在 .ts 文件中声明这个变量

    curIndex:number = null;
    

    请参考 stackblitz demo

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 2020-08-30
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多