初學(xué)Angular 時(shí)遇到過(guò)關(guān)于checkbox 雙向綁定的問(wèn)題,看代碼:
愛(ài)好:
<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}
]
};
運(yùn)行后,控制臺(tái)報(bào)錯(cuò):
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 標(biāo)簽添加name,或者使用[ngModelOptions]="{standalone: true}"。
添加name后,錯(cuò)誤消失,但又出現(xiàn)新的問(wèn)題。我的初始值之中‘登山’和‘游泳’是要被選中的,然鵝,運(yùn)行后并沒(méi)有選中,反復(fù)折騰后,終于發(fā)現(xiàn)問(wèn)題所在。因?yàn)槲宜械腸heckbox 使用的name 相同,而checkbox 的checked attr(關(guān)于attr 和prop 的區(qū)別請(qǐng)自行查找)的值以最后一個(gè)checkbox 的值為準(zhǔn)(原理沒(méi)搞懂)。也就是說(shuō),最后一個(gè)為true,則所有的都選中,最后一個(gè)為false,則都不選中。。。
無(wú)奈之下,我將name 刪除,用了第二種解決方案,即使用[ngModelOptions]="{standalone: true}",這一次成功初始化,該選的都選了。
雖然功能沒(méi)問(wèn)題了,但我還是有點(diǎn)小糾結(jié),就不能給checkbox 設(shè)置name 嗎?可能谷歌覺(jué)得使用了雙向綁定,你沒(méi)必要在使用form 表單提交來(lái)獲取數(shù)據(jù)吧!