【问题标题】:Set the default value to reactive control if nothing is entered如果未输入任何内容,则将默认值设置为反应控制
【发布时间】:2018-06-21 00:58:51
【问题描述】:

我的 Angular 应用程序中有反应形式,带有数字输入:

initForm() {
  this.form = this.fb.group(
    coffee: ['0', [
      Validators.min(0)
    ]],
    tea: ['0', [
      Validators.min(0)
    ]],
}

每个输入在初始化时都有“0”作为值,但用户可以删除值并保存表单。当用户保存表单时,我想为所有没有值的控件设置“0”。我怎样才能正确地做到这一点?

【问题讨论】:

  • 可以在对应控件上使用valueChanges事件,如果字段为空则设置默认值
  • @AbineshDevadas 真的,谢谢。为什么我没有立即考虑...)

标签: angular angular-reactive-forms


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2022-06-19
    相关资源
    最近更新 更多