jeudi 14 juillet 2022

Angular 2 checkbox to select all works but doesnt mark checkboxes

i've been using this implementation before and it worked, but i had to export whole logic to a service and now the toggleAll doesnt really work. It pushes every selected object to an array but checkboxes arent getting checked.

Checkbox-service logic:

    if(event.checked){
      this.selectedUsers.push(item);
    } else {
      const index = this.selectedUsers.indexOf(item);
      if(index >= 0){
        this.selectedUsers.splice(index, 1);
      }
    }
  }
  
  exists(item){
    return this.selectedUsers.indexOf(item) != -1;
  }
  
  isIndeterminate(){
    return (this.selectedUsers.length > 0 && !this.isChecked());
  }
  
   isChecked(){
     return this.selectedUsers.length === this.users.length;
    }
    
    toggleAll(event: MatCheckboxChange){
      if (event.checked){
        this.selectedUsers.length = 0;
        this.users.forEach(row=> {
          this.selectedUsers.push(row);
        })
      } else {
        this.selectedUsers.length = 0;
      }
    }

In my component im just returning every method

 getCheckboxData(){
    return this.checkboxDataService;
  }

Fragment of template with master-checkbox:

<button mat-raised-button (click)="onButtonClick()">Odśwież</button>
<div class="container" #loaded>
    <div class="row">
        <div class="col">
            <p>
                <mat-checkbox [checked]="getCheckboxData().isChecked()"
                [indeterminate]="getCheckboxData().isIndeterminate()"
                (change)="getCheckboxData().toggleAll($event)"
                ></mat-checkbox> Nazwa zadania</p>

And template with rest of the checkboxes:

<div class="container" *ngFor="let user of users">
        <div class="row">
            <div class="col">
                <mat-checkbox (click)="$event.stopPropagation()"
                (change)="$event ? getCheckboxData().toggle(user, $event) : null" 
                [checked]="getCheckboxData().exists(user)"></mat-checkbox>

Had to use service since i need to stream array with checked items to a different component.




Aucun commentaire:

Enregistrer un commentaire