Javascript 如何以编程方式将 Angular 2 表单控件设置为脏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37844092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:48:09  来源:igfitidea点击:

How do I programmatically set an Angular 2 form control to dirty?

javascriptangular

提问by Eran Shabi

How do I mark an Angular 2 Control as dirty in my code?

如何在我的代码中将 Angular 2 控件标记为脏?

When I do it like this:

当我这样做时:

control.dirty = true;

I get this error:

我收到此错误:

Cannot set property dirty of #<AbstractControl> which has only a getter

回答by Eran Shabi

You should use the markAsDirtymethod, like this:

您应该使用该markAsDirty方法,如下所示:

control.markAsDirty();

This will also mark all direct ancestors as dirty to maintain the model.

这也会将所有直接祖先标记为脏以维护模型。

Docs link

文档链接

回答by Yazan Khalaileh

Assuming that you call the method from your template as:

假设您从模板中调用该方法为:

<form #loginForm = "ngForm" (ngSubmit)="login(loginForm)"> ... </form>

In your login.component.ts, use the following

在您的 login.component.ts 中,使用以下内容

login(loginForm : any) {
    //make sure that inputs are valid
    if (loginForm.invalid) { 
      Object.keys( loginForm.controls).forEach(key => {
       loginForm.controls[key].markAsDirty();
      });
      return;
    }
}

回答by BlackBeard

You can write a custom function to mark allthe controls in a FormGroupas touched/dirty like this:

您可以编写一个自定义函数来将 a 中的所有控件标记FormGroup为已触摸/脏,如下所示:

  markFormGroupTouched(formGroup: FormGroup) {
    (<any>Object).values(formGroup.controls).forEach(control => {
      control.markAsDirty();  // or control.markAsTouched();
    });
  }

回答by Saravana Manikandan

For template driven forms we can use below generic code

对于模板驱动的表单,我们可以使用以下通用代码

 public onSubmitForm(cardFormObject: NgForm) {
        if (!cardFormObject.valid)
            this.markAsDerty(cardFormObject);      

    }

    private markAsDerty(cardFormObject: NgForm) {
        for (var eachControl in cardFormObject.controls) {
            (<FormControl>cardFormObject.controls[eachControl]).markAsDirty();
        }
    }