[英]Angular FormGroup receives no changes from child FormGroup
我有一個響應式 Angular 11 表單,它根據選擇動態構建附加控件。 這些控件都添加在父表單內的同一個 FormGroup 中並且是必需的,但是即使我填寫了每個字段,父表單仍然無效。
模板如下所示:
<form [formGroup]="emailForm" (ngSubmit)="onSubmit()">
<div class="template">
<label for="template">Template</label>
<select formControlName="template" id="template" required>
<option *ngFor="let template of templateNames" value="{{template}}">{{template}}</option>
</select>
</div>
<div class="language">
<label for="language">Language</label>
<select formControlName="language" id="language" required>
<option *ngFor="let language of templateLanguages" value="{{language}}">{{language}}</option>
</select>
</div>
<div class="placeholders" formGroupName="placeholders">
<p>Placeholders</p>
<div *ngFor="let placeholder of templatePlaceholders" class="placeholders__placeholder">
<label for="{{placeholder}}-field">{{placeholder}}</label>
<input id="{{placeholder}}-field" required type="text">
</div>
</div>
<div class="submit">
<input type="submit" value="Send" [disabled]="!emailForm.valid">
</div>
</form>
這是組件(大部分行為被剝離以保持示例最小且可重復):
public emailForm!: FormGroup;
public templateNames = ["one", "two", "three"];
public templateLanguages = ["en", "pt", "de"];
public templatePlaceholders: string[] = [];
ngOnInit(): void {
this.emailForm = new FormGroup({
template: new FormControl(),
language: new FormControl(),
placeholders: new FormGroup({}),
}, Validators.required);
this.populatePlaceholders();
}
populatePlaceholders(): void {
const placeholders: string[] = [];
// Some API call...
// ...
const placeholderFields: Record<string, FormControl> = {};
placeholders.forEach((placeholder) => {
placeholderFields[placeholder] = new FormControl("", Validators.required);
this.templatePlaceholders.push(placeholder);
});
this.emailForm.setControl("placeholders", new FormGroup(placeholderFields));
}
問題是,即使我填寫了每個字段,即使根本沒有占位符字段,提交按鈕仍然處於禁用狀態。 我已經嘗試在valueChanges
上記錄emailForm.placoholders
的狀態,我可以看到它保持不變(如果我在字段中輸入任何內容,該值不會顯示在其控件中),並且valueChanges
事件甚至沒有被觸發如果我在子字段中輸入任何內容,則僅當它位於第一級控件之一中時。
我對 Angular 很陌生,所以我一定做錯了什么,但是什么?
編輯:代碼的堆棧閃電戰: https://stackblitz.com/edit/angular-ivy-mdzjn8?file=src/app/app.component.ts
我發現了問題:我忘記將formControlName
屬性添加到模板中的控件。 我添加了formControlName="{{placeholder}}"
問題就解決了。
我希望像這樣的可忘記的事情有一個明確的錯誤; 真的很難調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.