简体   繁体   中英

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. 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. Is there any way of doing it a bit cleaner?

Here is what I've got so far:

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:

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. To do it in performant way in angular would be to do with ngFor and trackby. A sample imlementation is available at 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM