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
Adding the active class to each clicked button, Angular 4
提问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 singleisClicked
property on the component that is used by allbuttons. Instead, expand your buttons
array 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 isClicked
property, 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>