从 Angular 2 打字稿中的 HTML 获取复选框值。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40871351/
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
Get checkbox value from HTML in Angular 2 typescript.
提问by Roka545
I have two checkboxes in my html as follows:
我的 html 中有两个复选框,如下所示:
<label><input type="checkbox" id="checkbox1" /> Folder 1: </label>
<label><input type="checkbox" id="checkbox2" /> Folder 2: </label>
but I'm unsure of how to retrieve the checkbox values inside my Typescript file. I know I can accomplish this by calling a separate function for each checkbox and changing a value within my typescript. However, that doesn't seem like the best way - if I had ten different checkboxes then I would need 10 different functions in my typescript.
但我不确定如何检索我的 Typescript 文件中的复选框值。我知道我可以通过为每个复选框调用一个单独的函数并更改我的打字稿中的值来实现这一点。然而,这似乎不是最好的方法——如果我有十个不同的复选框,那么我的打字稿中将需要 10 个不同的函数。
Is there a simply way to get whether the checkbox is on or off based on the id? Is there a better way than that?
有没有一种简单的方法可以根据 id 获取复选框是打开还是关闭?还有比这更好的方法吗?
回答by andrea.spot.
If you want to two-way-bind the checkbox, you should use ngModel binding.
如果要双向绑定复选框,则应使用 ngModel 绑定。
<input type="checkbox" [(ngModel)]="checkBoxValue" />
and in your component's class:
并在您的组件类中:
export class AppComponent {
checkboxValue: boolean = false;
}
回答by Madhu Ranjan
you may bind to checked property of input
element like below,
您可以绑定到input
元素的检查属性,如下所示,
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>
<label><input type="checkbox" [checked]="checkbox1" /> Folder 1: </label>
<label><input type="checkbox" [checked]="checkbox2" /> Folder 2: </label>
`
})
export class AppComponent {
name = 'Angular';
checkbox1 = false;
checkbox2 = true;
}
Here is the Plunker.
这是Plunker。
Hope this helps!!
希望这可以帮助!!
回答by lastWhisper
You can use [value]="myVariable"
in checkboxes!
您可以[value]="myVariable"
在复选框中使用!