我的Angular应用中有反应式表单,其中有数字输入:
initForm() {
this.form = this.fb.group(
coffee: ['0', [
Validators.min(0)
]],
tea: ['0', [
Validators.min(0)
]],
}
每次输入时,每个输入的值都为“ 0”,但用户可以删除值并保存表格。当用户保存表单时,我想为所有不带值的控件设置“ 0”。我该如何正确执行此操作?
答案 0 :(得分:1)
save(): void {
const controlNames = Object.keys(this.form.controls);
for (const name of controlNames) {
if (this.form.get(name) && !this.form.get(name).value) {
this.form.get(name).setValue('0')
}
}
...remaining save logic elided since it's out of scope of the question
}