利用“@angular/forms" 創建<form>表單的時候,系統默認會創建一個”FormGroup"的對象。
使用帶有“ngModel"的”<input>“標簽時,系統會自動為這個標簽創建一個叫做”FormControl"的對象,並且會自動把它添加到”FormGroup"中。而“FormControl"在”FomGroup“中是用"<input>"標簽上的”name"屬性來做標識的。
例如下面這個例子:
<form #f="ngForm"> <input type="text" [(ngModel)]="firstFieldVariable" name="firstField"> <span>{{ f.controls['firstField']?.value }}</span> </form>
如果沒有使用“name”這個屬性,那系統就會報錯:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable"> </form>
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.
解決方法除了把“name”屬性添加上外,還有第二種選擇,就是給"<input>"標簽設置一個
ngModelOptions
屬性:
[ngModelOptions]="{standalone: true}"
當設置了這個屬性,<input>的 FormControl 對象就不會添加到FormGroup內,也就不能通過
{{ f.controls['firstField']?.value }} 索引到該對象的值了。
參考: https://github.com/angular/angular/issues/9230#issuecomment-228116474