Html Angular 2 Checkbox 双向数据绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40214655/
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
Angular 2 Checkbox Two Way Data Binding
提问by Junias
I′m fairly new to Angular2 and I have a little problem:
我是 Angular2 的新手,我有一个小问题:
In my Login-Component-HTML, I have two checkboxes, which I want to bind in two way data-binding to the Login-Component-TypeScript.
在我的 Login-Component-HTML 中,我有两个复选框,我想以两种方式将它们绑定到 Login-Component-TypeScript。
This is the HTML:
这是 HTML:
<div class="checkbox">
<label>
<input #saveUsername [(ngModel)]="saveUsername.selected" type="checkbox" data-toggle="toggle">Save username
</label>
</div>
And this is the Component.ts:
这是 Component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Variables } from '../../services/variables';
@Component({
selector: 'login',
moduleId: module.id,
templateUrl: 'login.component.html',
styleUrls: ['login.component.css']
})
export class LoginComponent implements OnInit {
private saveUsername: boolean = true;
private autoLogin: boolean = true;
constructor(private router: Router, private variables: Variables) { }
ngOnInit() {
this.loginValid = false;
// Get user name from local storage if you want to save
if (window.localStorage.getItem("username") === null) {
this.saveUsername = true;
this.autoLogin = true;
console.log(this.saveUsername, this.autoLogin);
} else {
console.log("init", window.localStorage.getItem("username"));
}
}
login(username: string, password: string, saveUsername: boolean, autoLogin: boolean) {
this.variables.setUsername(username);
this.variables.setPassword(password);
this.variables.setIsLoggedIn(true);
console.log(saveUsername, autoLogin);
//this.router.navigate(['dashboard']);
}
If I click an checkbox, I get the correct value in the controller (component).
如果我单击一个复选框,我会在控制器(组件)中获得正确的值。
But if I change the value of for example saveUsername
in the component, the checkbox didn't "get" the new value.
但是,如果我更改了例如saveUsername
组件中的值,则复选框不会“获取”新值。
So I can′t manipulate the checkbox from the Component (like I want to do in the ngOnInit
in the component.
所以我不能从组件中操作复选框(就像我想ngOnInit
在组件中做的那样。
Thanks for your help!
谢谢你的帮助!
回答by hakany
You can remove .selected
from saveUsername
in your checkbox input since saveUsername is a boolean. Instead of [(ngModel)]
use [checked]="saveUsername" (change)="saveUsername?=?!saveUsername"
您可以.selected
从saveUsername
复选框输入中删除,因为 saveUsername 是一个布尔值。而不是[(ngModel)]
使用[checked]="saveUsername" (change)="saveUsername?=?!saveUsername"
Edit: Correct Solution:
编辑:正确的解决方案:
<input
type="checkbox"
[checked]="saveUsername"
(change)="saveUsername = !saveUsername"/>
Update:Like @newman noticed when ngModel
is used in a form it won't work. However, you should use [ngModelOptions]
attribute like (tested in Angular 7):
更新:就像@newman 注意到ngModel
在表单中使用时它不起作用。但是,您应该使用[ngModelOptions]
类似的属性(在 Angular 7 中测试):
<input
type="checkbox"
[(ngModel)]="saveUsername"
[ngModelOptions]="{standalone: true}"/> `
I also created an example at Stackblitz: https://stackblitz.com/edit/angular-abelrm
我还在 Stackblitz 创建了一个例子:https://stackblitz.com/edit/angular-abelrm
回答by Ruslan Makrenko
Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.
不幸的是,@hakani 提供的解决方案不是双向绑定。它只是处理来自 UI/FrontEnd 部分的单向更改模型。
Instead the simple:
取而代之的是简单的:
<input [(ngModel)]="checkboxFlag" type="checkbox"/>
will do two-way binding for checkbox.
将对复选框进行双向绑定。
Afterwards, when Model checkboxFlagis changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.
之后,当模型checkboxFlag从后端或 UI 部分更改时- 瞧,checkboxFlag 存储实际的复选框状态。
To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
为了确保我已经准备好 Plunker 代码来呈现结果:https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
Just to complete this answer you should include the import { FormsModule } from '@angular/forms'
into app.module.ts
and add to imports array i.e
只是为了完成这个答案,你应该包括import { FormsModule } from '@angular/forms'
进入app.module.ts
并添加到导入数组即
import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
回答by Kris Kilton
I'm working with Angular5 and I had to add the "name" attribute to get the binding to work... The "id" is not required for binding.
我正在使用 Angular5,我必须添加“name”属性才能使绑定工作......绑定不需要“id”。
<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">
回答by MovGP0
I prefer something more explicit:
我更喜欢更明确的东西:
component.html
组件.html
<input #saveUserNameCheckBox
id="saveUserNameCheckBox"
type="checkbox"
[checked]="saveUsername"
(change)="onSaveUsernameChanged(saveUserNameCheckBox.checked)" />
component.ts
组件.ts
public saveUsername:boolean;
public onSaveUsernameChanged(value:boolean){
this.saveUsername = value;
}
回答by Jose Alberto Fernandez
When using <abc [(bar)]="foo"/>
syntax on angular.
<abc [(bar)]="foo"/>
在 angular 上使用语法时。
This translates to:
<abc [bar]="foo" (barChange)="foo = $event" />
这转化为:
<abc [bar]="foo" (barChange)="foo = $event" />
Which means your component should have:
这意味着您的组件应该具有:
@Input() bar;
@Output() barChange = new EventEmitter();
回答by Nuno Ferro
You can just use something like this to have two way data binding:
您可以使用这样的东西来进行两种方式的数据绑定:
<input type="checkbox" [checked]="model.property" (change)="model.property = !model.consent_obtained_ind">
回答by M.Shakeri
You must add name="selected"
attribute to input
element.
您必须name="selected"
向input
元素添加属性。
For example:
例如:
<div class="checkbox">
<label>
<input name="selected" [(ngModel)]="saveUsername.selected" type="checkbox">Save username
</label>
</div>
回答by Mahdi Shahbazi
To get checkbox work you should follow all these steps:
要使复选框工作,您应该遵循以下所有步骤:
- import
FormsModule
in your module - Put the input inside a
form
tag your input should be like this:
<input name="mpf" type="checkbox" [(ngModel)]="value" />
Note: do not forget to put name in your input.
FormsModule
在您的模块中导入- 将输入放在
form
标签内 你的输入应该是这样的:
<input name="mpf" type="checkbox" [(ngModel)]="value" />
注意:不要忘记在输入中输入名称。
回答by user1786641
I have done a custom component tried two way binding
我做了一个自定义组件尝试了两种方式绑定
Mycomponent:
<input type="checkbox" [(ngModel)]="model" >
我的组件:
<input type="checkbox" [(ngModel)]="model" >
_model: boolean;
@Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>();
@Input('checked')
set model(checked: boolean) {
this._model = checked;
this.checked.emit(this._model);
console.log('@Input(setmodel'+checked);
}
get model() {
return this._model;
}
strange thing is this works
奇怪的是这是有效的
<mycheckbox [checked]="isChecked" (checked)="isChecked = $event">
while this wont
虽然这不会
<mycheckbox [(checked)]="isChecked">
回答by Sabbir
In any situation, if you have to bind a value with a checkbox which is not boolean then you can try the below options
在任何情况下,如果您必须使用非布尔值的复选框绑定值,那么您可以尝试以下选项
In the Html file:
在 Html 文件中:
<div class="checkbox">
<label for="favorite-animal">Without boolean Value</label>
<input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'"
(change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'">
</div>
in the componentischeckedWithOutBoolean: any = 'Y';
在组件中ischeckedWithOutBoolean: any = 'Y';
See in the stackblitz https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html
请参阅stackblitz https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html