[英]Angular10 - Change multiple css id with onClick event
I am having some trouble trying to change the css of a button with the (click) event.我在尝试使用(单击)事件更改按钮的 css 时遇到了一些麻烦。 I managed to do it, but the problem is that I have 10 buttons, so I can't depend on one variable in the.ts because once it changes, it will affect all 10 buttons and not just the one which was clicked, so the only thing I thought was having 10 different variables, but it is not quite elegant.
我设法做到了,但问题是我有 10 个按钮,所以我不能依赖 .ts 中的一个变量,因为一旦它发生变化,它将影响所有 10 个按钮,而不仅仅是被点击的那个,所以我唯一想到的是有 10 个不同的变量,但它不是很优雅。 Is there any way of doing it a bit cleaner?
有没有办法让它更干净一点?
Here is what I've got so far:这是我到目前为止所得到的:
html: html:
<button (click)="b1 = !b1" class="tarea" [id]="cambiaId(b1)"></button>
<button (click)="b2 = !b2" class="tarea" [id]="cambiaId(b2)"></button>
<button (click)="b3 = !b3" class="tarea" [id]="cambiaId(b3)"></button>
[...]
<button (click)="b10 = !b10" class="tarea" [id]="cambiaId(b10)"></button>
ts: ts:
export class TareasComponent {
b1 : boolean = false;
b2 : boolean = false;
b3 : boolean = false;
[...]
b10 : boolean = false;
cambiaId(b : boolean){
if (b) {
return "done";
}else{
return "todo";
}
}
I think you might have some valid reason to have duplicate id for elements.我认为你可能有一些正当的理由让元素有重复的 id。 To do it in performant way in angular would be to do with ngFor and trackby.
在 angular 中以高性能的方式执行此操作将与 ngFor 和 trackby 有关。 A sample imlementation is available at CodeSandbox Implementation
CodeSandbox Implementation提供了一个示例实现
buttons: ButtonType[] = Array(10).fill("todo").map((value, i) => ({ id: i, value })); trackById(index: number, button: ButtonType) { return button.id; } buttonClicked(index: number, button: ButtonType) { const ret = this.buttons.slice(0); ret[index] = {...button, value: button.value? "done": "todo" }; this.buttons = ret; }
<ng-container *ngFor="let item of buttons; index as i; trackBy:trackById"> <button [id]="item.value" (click)="buttonClicked(i, item)" class="tarea"> {{item.value}} </button> </ng-container>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.