初学Angular 时遇到过关于checkbox 双向绑定的问题,看代码:
爱好:
<span *ngFor="let item of userInfo.hobby; let key = index;">
<input type="checkbox" [id]="'check'+key" [(ngModel)]="item.checked" /><label [for]="'check'+key">{{item.title}}</label>
</span>
userInfo = {
hobby: [
{title: '跑步', checked: false},
{title: '登山', checked: true},
{title: '游泳', checked: true},
{title: '手游', checked: false}
]
};
运行后,控制台报错:
ERROR Error: "If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">"
Angular 9
View_RegisterFormComponent_2 RegisterFormComponent.html:17
Angular 31
RegisterFormComponent.html:17:6
嗯嗯,意思是如果使用ngModel,那么必须要给form 标签添加name,或者使用[ngModelOptions]="{standalone: true}"。
添加name后,错误消失,但又出现新的问题。我的初始值之中‘登山’和‘游泳’是要被选中的,然鹅,运行后并没有选中,反复折腾后,终于发现问题所在。因为我所有的checkbox 使用的name 相同,而checkbox 的checked attr(关于attr 和prop 的区别请自行查找)的值以最后一个checkbox 的值为准(原理没搞懂)。也就是说,最后一个为true,则所有的都选中,最后一个为false,则都不选中。。。
无奈之下,我将name 删除,用了第二种解决方案,即使用[ngModelOptions]="{standalone: true}",这一次成功初始化,该选的都选了。
虽然功能没问题了,但我还是有点小纠结,就不能给checkbox 设置name 吗?可能谷歌觉得使用了双向绑定,你没必要在使用form 表单提交来获取数据吧!