jeudi 21 juillet 2022

How do I fix a TypeError regarding a ViewChild element that actually works?

This is the HTML component where checkbox is

 <mat-checkbox class="dashboard-content-custom-select-option" id="dashboard-all-checkbox" #allSelector [indeterminate]="someCheckboxesActive()" [checked]="allCheckboxesActive()" (click)="toggleAllSelection($event)">Alle </mat-checkbox>
The Select all Mat-Checkbox is checked if all of the upper checkboxes are checked. It is also checked if clicked on while some checkboxes are left empty and all of them are checked.
export class DashboardContentComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('dashboard-all-checkbox') allSelect: MatCheckbox;

toggleAllSelection(event) { // toggle checkbox is controlled from here
    console.log(this.allSelect);
    if ( event.currentTarget.id === 'dashboard-all-checkbox' && this.selectedValues.length === 6) {
      this.dashboardContentForm.get('dashboardContentValue').setValue([]); 
      this.allSelect.checked = false; // unchecks the checkbox
    } else if ( (this.selectedValues.length < 6  && event.currentTarget.id === 'dashboard-all-checkbox') )  {
      this.dashboardContentForm.get('dashboardContentValue').setValue(
         [ ...this.displayDashboardContentValues.map((dv) => dv.key), ...[0]]
      );
      this.allSelect.toggle(); //checks the checkbox
    }
  }
}
In this TS file, 6 upper checkboxes must all be active for the Select All checkbox to be active. Otherwise if less than 6 are active, it becomes indeterminate.

To be precise, everything works fine. However, the only problem is that I get TypeErrors although the checkbox does whatevery it is supposed to do. If checkbox's id is used, everything is fine(which is the only way that works here in my case). If I use the #allSelector, it is different. How do I prevent these errors from occuring? Besides, you can ignore the grey highlighting in the dropdown, it isn't relevant.

if the select all checkbox is clicked and checked enter image description here

enter image description here

if the select all checkbox is clicked and unchecked enter image description here

enter image description here




Aucun commentaire:

Enregistrer un commentaire