typescript 将活动类添加到每个点击的按钮,Angular 4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47752719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:06:34  来源:igfitidea点击:

Adding the active class to each clicked button, Angular 4

angulartypescript

提问by Cheese Fox

I have:

我有:

<button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked"

Result:

结果:

10x button on screen.

屏幕上的 10x 按钮。

When I click on the button number 1: Each button will get class ".active"

当我单击按钮编号 1 时:每个按钮将获得类“.active”

But I would like:

但我想:

When I click buttonnumber 1: will get class ".active".

当我点击按钮1:将获得一流的“主动”。

When I click buttonnumber 3: will get class ".active".

当我点击按钮3:将获得一流的“主动”。

When I click buttonnumber 6: will get class ".active".

当我点击按钮6:将获得一流的“主动”。

Result:

结果:

Button 1, Button 3, Button 6- Each this buttons will get class ".active"

按钮 1按钮 3按钮 6- 每个此按钮都将获得类“.active”

How to do that?

怎么做?

PLUNKER: https://plnkr.co/edit/lX3DjN46STmo6gfBkPCc?p=preview

PLUNKER:https://plnkr.co/edit/lX3DjN46STmo6gfBkPCc ?p =preview

回答by Paka

Just maintain a temporary array

只维护一个临时数组

<button *ngFor="let button of [1,2,3,4]; let i = index" [ngClass]="{'active':isClicked[i]}" (click)="isClicked[i] = (isClicked[i]? false :true )">button</button>

in component public isClicked = [];

在组件中 public isClicked = [];

working fiddler --> https://plnkr.co/edit/MwuWhtBPPQUQCG2Y9qmx?p=preview

工作小提琴手 --> https://plnkr.co/edit/MwuWhtBPPQUQCG2Y9qmx?p=preview

Hope it helps!!

希望能帮助到你!!

回答by Kirk Larkin

When you use (click)="isClicked = !isClicked", you set a singleisClickedproperty on the component that is used by allbuttons. Instead, expand your buttonsarray to an array of objects:

当你使用(click)="isClicked = !isClicked",你设定一个单一isClicked所使用的组件属性所有的按钮。相反,将buttons数组扩展为对象数组:

buttons = [
    { text: 'item1', isClicked: false },
    { text: 'item2', isClicked: false },
    { text: 'item3', isClicked: false },
    // ...
]

With this, each button has its own isClickedproperty, which you can use like this:

有了这个,每个按钮都有自己的isClicked属性,你可以这样使用:

<button *ngFor="let button of buttons" [ngClass]="{'active': button.isClicked}" (click)="button.isClicked = !button.isClicked">
    {{ button.text }}
</button>

Here's an updated plunker.

这是一个更新的 plunker