简体   繁体   English

Angular 10 中的复选框选中状态

[英]Checkbox checked state in Angular 10

I am using Angular 10. I have a checkbox in my html file.我正在使用 Angular 10。我的 html 文件中有一个复选框。 In my typescript file I want to see if the checkbox is checked or not and perform some action accordingly.在我的打字稿文件中,我想查看复选框是否被选中并相应地执行一些操作。 Is there a way to get the checked state of the checkbox like true if it is checked and false otherwise?有没有办法让复选框的选中状态像 true 一样被选中,否则为 false? TIA. TIA。

To my knowledge, we have two ways of checking the state of the checkbox:据我所知,我们有两种检查复选框状态的方法:

  1. Use the library for angular, Ex: Material UI: https://material.angular.io/components/checkbox/examples or different libraries.使用 angular 库,例如:Material UI: https : //material.angular.io/components/checkbox/examples或不同的库。
  2. Use two-way binding of angular [(ngModel)] ="checked" on the HTML template在 HTML 模板上使用 angular [(ngModel)] ="checked" 的双向绑定

you can use two-way binding like this你可以像这样使用双向绑定

html html

<input type="checkbox" [(ngModel)]="checked">

ts ts

checked = false;

You can use change event to check the state您可以使用更改事件来检查状态

<input type="checkbox" (change)="onSelect($event.target.checked)">


onSelect(state:boolean) {
     console.log("Is Checked? ", state)
}

If you are not using Template Form or Reactive Form,如果您不使用模板表单或响应式表单,

<input type="checkbox" (change)="changeEvent($event.target.checked)">

For Template Forms,对于模板表单,

<input type="checkbox" [(ngModel)]='checked' (ngModelChange)="changeEvent()">

For reactive forms,对于反应形式,

<input type="checkbox" formControlName='check'>

this.form.get('check').valueChanges
.subscribe((check)=> this.changeEvent())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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