Javascript 如何以角度获取复选框值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50945978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get checkbox value in angular?
提问by naveen
can you please tell me a way to get checkbox value in angular 2
你能告诉我一种在角度 2 中获取复选框值的方法吗
here is my code
这是我的代码
https://stackblitz.com/edit/angular-grtvc7?file=src%2Fapp%2Fapp.module.ts
https://stackblitz.com/edit/angular-grtvc7?file=src%2Fapp%2Fapp.module.ts
one way I know how to do that using the template variable like this
我知道如何使用这样的模板变量来做到这一点的一种方式
<mat-checkbox #ch>Check me!</mat-checkbox>
checkCheckBoxvalue(ele){
console.log(ele.checked)
}
I want to know another way to achieve this functionality
我想知道实现此功能的另一种方法
回答by Pardeep Jain
you need to use changeevent
你需要使用change事件
<mat-checkbox (change)="checkCheckBoxvalue($event)">Check me!</mat-checkbox>
checkCheckBoxvalue(event){
console.log(event.checked)
}
回答by Anthony Agbator
bind an [ngModel] to the checkbox
将 [ngModel] 绑定到复选框
<input type="checkbox" name="checkbox" [(ngModel)]="isChecked">
const isChecked : boolean;
回答by Vishaal Kathiriya
Using Template-Driven Form
使用模板驱动的表单
1. Creating Checkbox
1. 创建复选框
We need to use ngModel as an attribute in checkbox so that they can be registered with NgForm directive.
我们需要在复选框中使用 ngModel 作为属性,以便它们可以使用 NgForm 指令进行注册。
Create checkbox:
创建复选框:
<input type="checkbox" name="tc" ngModel>
2. Fetch Value on Form Submit
2. 在表单提交时获取值
When we submit the form and suppose the form value is stored in the instance of NgForm as form then we can fetch checkbox value using form.controls[...] as given below.
当我们提交表单并假设表单值作为表单存储在 NgForm 的实例中时,我们可以使用 form.controls[...] 获取复选框值,如下所示。
this.user.isTCAccepted = form.controls['tc'].value;
回答by Peter Wilson
as you already have a local reference #cyou can use it on the component ts file when needed
由于您已经有了本地引用,因此#c您可以在需要时在组件 ts 文件中使用它
import {ViewChild} from '@angular/core';
@ViewChild('c') checkbox;
// when needed
//this.checkbox.value
you can call it on form submit or on change event of the checkbox itself.
您可以在表单提交或复选框本身的更改事件上调用它。
回答by Ulrich Dohou
You can use ngModelas you already have imported FormsModule. Thats the recommended way.
Check my stackblitz
您可以使用ngModel已经导入的FormsModule. 那是推荐的方式。检查我的堆栈闪电战
Here is some code also
这里还有一些代码
View
看法
<mat-checkbox [(ngModel)]="checkBoxValue" [ngModelOptions]="{standalone: true}">Check me!</mat-checkbox>
<button (click)="checkCheckBoxvalue()">check check box value</button>
Component
成分
checkBoxValue: any = false;
checkCheckBoxvalue(){
console.log(this.checkBoxValue)
}

