Angular FormGroup不会从子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));
}

问题是,即使我填写了每个字段,即使根本没有占位符字段,提交按钮仍然是禁用的。我试着记录emailForm.placoholdersvalueChanges上的状态,我可以看到它保持不变(如果我在字段中输入任何东西,该值不会显示在其控件中),如果我在子字段中输入任何东西,valueChanges事件甚至不会触发,只有当它在第一级控件之一时。

我对Angular很陌生,所以我一定是做错了什么,但是什么呢?

编辑:代码的集锦:https://stackblitz.com/edit/angular-ivy-mdzjn8?file=src/app/app.component.ts

我发现了问题:我忘记将formControlName属性添加到模板中的控件中。我添加了formControlName="{{placeholder}}",问题就解决了。

我希望像这样容易忘记的事情有一个明确的错误;这真的很难调试。

最新更新