Angular 2 中的复选框双向数据绑定
这篇有 Angular 的文章将着眼于执行复选框双向数据绑定的不同方法。
我们将使用 ngModelOptions
属性进行双向数据绑定。当存在 name
属性时,此解决方案最有效。
我们还将介绍 ngModel
属性,该属性使 checkboxFlag
能够在更改时存储实际的复选框状态。然后我们将使用 change
属性进行数据绑定,这样当组件中的值发生更改时,复选框也会获得一个新值。
在表单中使用 ngModel
时,它通常不起作用,因此最好使用 ngModelOptions
属性来确保复选框值随着组件中的数据更改而更改。
<input
type="checkbox"
[(ngModel)]="itemChange"
[ngModelOptions]="{standalone: true}"/>
在某些情况下,如果输入不在表单内而是构成 ngFor
循环的一部分,则代码将不起作用。此外,name
属性需要包含在代码设置中才能使代码正常工作。
虽然上面的示例代码在前端部分处理双向数据绑定,但此解决方案在后端执行更改,正确使用 ngModel
。
<input
[(ngModel)]="itemOne">
type="checkbox"/>
为了让这段代码完美运行,将 { FormsModule }
从 @angular/forms
导入 app.module.ts
并添加到导入数组中,如下所示:
import { FormsModule } from'@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
name
属性必须是唯一的,默认选中状态才能按预期工作,并且它必须在 input
标签内。但是,如果你在重复对象数组时使用 ngFor
中的复选框,则此代码将不起作用,如下所示:
[{"checked":true},{"checked":false}]
然后我们也可以使用 change
属性在复选框上进行数据绑定。通过这种方法,我们可以更详细地创建代码。
html 组件将如下所示:
<input #saveCheckboxOne
id="saveCheckboxOne"
type="checkbox"
[checked]="saveCheckbox"
(change)="onSaveCheckboxChange(saveUserNameCheckBox.checked)" />
然后 component.js 会像下面这样写。
public saveCheckbox:boolean;
public onSaveCheckboxChange(value:boolean){
this.saveUsername = value;
}
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。