how to programmatically set or reset checkbox

Viewed 16109

Purpose: when a particular checkbox is checked or unchecked, the program must change a number of other checkboxes according to programmed rules.

<input type="checkbox" id="chkbox" (change)="onChangeChk($event)">Test Checkbox

  onChangeChk($event) {
    $event.srcElement.value = "on"; // or "off"
  }

The checkbox remains in its original state no matter how the onChangeChk sets it.

Thanks for you help on this. :-)

2 Answers

If you have a CheckBox:

<mat-checkbox
  [checked]="filterStatusPrivatUser"
  #privatUserCheckbox>Privat User</mat-checkbox>

You can access the checked attribute using ViewChild like so:

import { ElementRef } from '@angular/core';

filterStatusPrivatUser: boolean = true;

@ViewChild('privatUserCheckbox') privatUserCheckbox: ElementRef;

And then change the value programatically like so:

changeCheckboxProgramatically() {
    this.privatUserCheckbox['checked'] = true;
}
Related