【问题标题】:Typescript / Angular 8: Change individual button color displayed using ngForTypescript / Angular 8:使用 ngFor 更改显示的单个按钮颜色
【发布时间】:2020-11-13 07:13:55
【问题描述】:

我正在使用 ngFor 指令显示文本(逐字)。在 ngFor 中,我有一个 if-else-statement,它的条件确定一个词是显示为 <span> 还是 <button> - 这已经可以了。

关于按钮,我希望它们的行为方式如下:在第一次单击单个按钮时,只有此按钮应将背景颜色更改为红色,再次单击时背景颜色应更改为灰色之前。

到目前为止,我编写的代码更改了所有按钮的按钮背景颜色,而不仅仅是单击的单个按钮。 我怎样才能改变只有一个按钮改变它的颜色?

HTML:

<div id="learnerText" *ngFor="let item of wordsJsonText; let i = index" [ngClass]="{active: i === activeIndex}">
  <div class="container" id="textBody" id="learnerText">
    <ng-container *ngIf="item.is_title==='false' && item.has_context==='false'; then caseA else caseB">
    </ng-container>
    <ng-template #caseA id="textBody" id="learnerText">
      <span id="learnerText">{{item.form}}</span>
    </ng-template>
    <ng-template #caseB>        
        <div *ngIf="item.is_title==='false' && item.has_context==='true'">
          <Button class="btn btn-secondary" [ngStyle]="{'background-color' : toggle ? 'red' : 'grey'}"
          id="bodyButton" text=item.form (click)="onClickMe(item.lemma, item.pos); toggleColor()">{{item.form}}</Button>
        </div>
    </ng-template>
  </div>
</div>

打字稿

private toggle: boolean;

toggleColor() {
    this.toggle = !this.toggle;
}

【问题讨论】:

  • 所有background-colors 都绑定到同一个变量toggle,这就是它们都发生变化的原因。让我寻找一个简单的解决方案。

标签: angular typescript ngfor


【解决方案1】:

在我看来,最简单的方法是简单地在每个对象下的 wordsJsonText 数组中添加一个额外的字段 - 比如toggled: boolean

[{form: 'abc', toggled: false}, {form: 'def', toggled: false}]

然后您可以在按钮上执行以下操作。

(click)="item.toggled = !item.toggled"

然后您可以使用此item.toggled 值将类分配给按钮。

【讨论】:

  • 因为我不想更改 json,所以我尝试了在我的打字稿代码中添加布尔值的方法,如下面的答案所示。不过谢谢!
【解决方案2】:

我会尝试以下方法

export interface JsonWordWrapper {
    jsonWord: JsonWord;
    checked: boolean;
}

toggleColor(item: JsonWrapper) {
    item.checked = !item.checked;
}

在您分配 wordsJsonText 变量的地方,而不是

this.wordsJsonText = wordsJson

使用

this.wordsJsonText = wordsJson.map<JsonWrapper>(w => {
    jsonWord: w,
    checked: false
});

你的 html 会是

<button [ngStyle]="{'background-color' : item.checked ? 'red' : 'grey'}" (click)="toggleColor(item)" ...>{{ item.jsonWord.form }}</button>

这样你就有了一个通用的方法,而不用改变你在 json 中的初始数据结构

【讨论】:

  • 我使用您的想法找到了解决问题的方法。我在阅读 wordsJsonText 时添加了布尔变量“checked”——没有创建额外的界面。然后我按照你的建议更改了 html 并返回了带有函数“toggleColor”的项目,该函数由相同的打字稿函数读取,就像你发布的那样。现在按钮颜色变化完美。谢谢!
猜你喜欢
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
相关资源
最近更新 更多