【问题标题】:patchvalue or setvalue of formbuilder does not mark field as dirty or touchedformbuilder 的 patchvalue 或 setvalue 不会将字段标记为脏或已触及
【发布时间】:2018-06-02 05:44:09
【问题描述】:

我有一个多步骤表单,用户在表单中来回遍历。我将表单数据保存在服务中,当他回来时,我使用 patchValue 修补所有数据以形成表单。我也尝试了 setValue,但表单字段没有被标记为脏的或被触摸的。如何将更新的字段标记为脏和已触摸?

this.formBuilder.patchValue(formData);

【问题讨论】:

    标签: angular angular4-forms


    【解决方案1】:

    您可以在表单对象上使用markAsDirty()markAsTouched() 方法显式标记表单。见API Here

    this.formName.markAsDirty()
    this.formName.markAsTouched()
    

    更新

    从 Angular 8 开始,您可以使用 markAllAsTouched 将所有表单字段标记为 touched

    this.formName.markAllAsTouched()
    

    【讨论】:

    • 但这不会标记其值已更改为脏的字段吗?
    • 我演示了表单级别的脏东西。您也可以在现场级别进行
    • 我也遇到了这个问题,尽管可以使用您引用的方法,但似乎我们不应该手动进行。我的观点是,如果新值与旧值不同并自动设置相应的标志,那么进行角度验证会很好。
    • @AntónioQuadrado 只有用户交互设置脏标志。这是故意的。请参阅此讨论:github.com/angular/angular/issues/9768
    【解决方案2】:

    我为这个问题找到的唯一解决方案就是它。

     this.form = this.formBuilder.group({
          id:[null],
          name: ValidatorsUtil.name(),
          lastName: ValidatorsUtil.required(),
          email: ValidatorsUtil.email(),
          phone: ValidatorsUtil.required(),      
        });
    
    this.form.setValue(this.client, {emitEvent: true});
    
    Object.keys(this.form.controls).forEach( controlKey => {
           this.form.controls[controlKey].markAsDirty();
         });
    

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2017-08-02
      • 2021-02-17
      • 2011-06-11
      • 2017-03-24
      相关资源
      最近更新 更多