範本中的某個 formControlName 指向一個 FormGroup 裡不存在的控制項。這個指令會依路徑查找控制項,卻什麼都找不到。
當範本與表單群組由同一份資料建構、卻使用不同的篩選條件時,就可能發生這種情況。某個項目被渲染到範本中,卻從未在表單群組裡獲得控制項,因此它的 formControlName 沒有任何東西可以繫結。
@Component({
template: `
<form [formGroup]="form">
<ng-container formGroupName="options">
@for (id of visibleIds; track id) {
<input [formControlName]="id" />
}
</ng-container>
</form>
`,
})
class App {
// The template renders an input for both ids...
visibleIds = [1, 2];
// ...but the form group only has a control for id 1.
form = new FormGroup({
options: new FormGroup({
1: new FormControl(''),
}),
});
}
如何除錯
錯誤訊息會列出該層級實際存在的控制項,例如:
Cannot find control with path: 'options -> 2'. Controls that do exist at this level: 1.
把它和你的範本所繫結的名稱比對。接著,將缺少的控制項加入 FormGroup,或停止為沒有控制項的項目渲染 formControlName。