how to programmatically set or reset checkbox

可紊 提交于 2020-02-28 23:13:14

问题


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. :-)


回答1:


You can assign the checked property of your input element to true or false.

Like so:

onChangeChk($event) {
    $event.srcElement.checked = true; // or false
}

See also here : https://www.w3schools.com/jsref/prop_checkbox_checked.asp




回答2:


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;
}


来源:https://stackoverflow.com/questions/45699783/how-to-programmatically-set-or-reset-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!