Typescript/Angular 8:使用ngFor更改显示的单个按钮颜色



我正在显示一个带有ngFor指令的文本(逐字(。在ngFor中,我有一个if-else语句,该语句带有一个条件,用于确定一个单词是显示为<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;
}

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

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

然后你可以在你的按钮上做以下操作。

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

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

我会尝试以下

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 中初始数据结构的情况下获得通用方法

最新更新