我有一个我构建的 Angular 表单,它由一个材料复选框组件组成。我有这个组件的两个副本,一个是静态的,一个是动态的。唯一的区别是动态版本从 API 调用中获取其控制值。这两个示例都有一个或多个选项,在控件初始化时默认为选中。
我遇到的问题是动态模型与其视图不同步,只要它保持不变(即,如果我不单击任何复选框控件来选择或取消选择它们)。单击其中一个复选框后,模型会更新以与视图同步。
我可以告诉这一点,因为我可以提交静态版本并获得预期的结果(默认项目按预期作为值发布)。但是,当我提交动态的时,我得到一个空帖子。
这是组件在我提交它以查看提交的表单数据之前使用默认值的样子:
这是结果提交的值(如预期的那样):
作为比较,这里是相同的控件(material-checkboxes.component.ts),但使用外部数据源构建以馈入 titleMap,并且还具有默认值。
这是提交上述表格后的结果:
因此,正如屏幕截图所示,手动创建的文件按预期工作,并提交包含默认值的表单。但是,具有动态生成值的组件,即使视图显示它已选择默认选项,也会作为 EMPTY 提交。
预期:this.controlValue = ['12', 'd4']
实际的:
onInit > this.controlValue = ['12', 'd4']
updateValue 方法后 > this.controlValue = undefined // 但是视图从初始化开始没有变化
但是,如果我手动更改任何值,我可以让它按预期提交数据,即使我将它们完全设置为默认值。就好像在手动单击选项之前没有设置表单数据。
以下是包含该组件的模板的片段:
<mat-checkbox
type="checkbox"
[class.mat-checkboxes-invalid]="showError && touched"
[class.mat-checkbox-readonly]="options?.readonly"
[checked]="allChecked"
[disabled]="(controlDisabled$ | async) || options?.readonly"
[color]="options?.color || 'primary'"
[indeterminate]="someChecked"
[name]="options?.name"
(focusout)="onFocusOut()"
(change)="updateAllValues($event)"
[required]="required"
[value]="controlValue">