Set Form to Pristine without clearing data

前端 未结 7 1523
暖寄归人
暖寄归人 2021-01-31 07:35

I have a form that displays a list of elements. They all share a common save button which is disabled until the form becomes dirty. Then

相关标签:
7条回答
  • 2021-01-31 07:37

    When using Angular's reactive forms, you can use markAsPristine() on the FormGroup:

    export class MyPage
    
      // Your form group
      public formGroup: FormGroup;
    
      ngOnInit() {
        this.formGroup = this.formBuilder.group({
          // Add your form controls here
        });
      }
    
      onSubmitForm() {
        // Get form value and save data on the server
        // ...
    
        this.formGroup.markAsPristine(); // <=== Mark form group as pristine
      }
    }
    

    See also: documentation for AbstractControl.markAsPristine(). Note: FormGroup is a subclass of AbstractControl. It will mark all children of the FormGroup as pristine.

    0 讨论(0)
  • 2021-01-31 07:42

    What you're looking for is myForm.form.markAsPristine().

    0 讨论(0)
  • 2021-01-31 07:43

    I think i solve done this on my method:

    form.controls['contato'].reset();

    0 讨论(0)
  • 2021-01-31 07:46

    I haven't found a markAsPristine() in the form property, but I found a _pristine property, this.myForm['form']._pristine which can be set to true.

    @ViewChild('myForm') myForm: ElementRef;
    this.myForm['form']._pristine = true;
    
    0 讨论(0)
  • 2021-01-31 07:59

    If you happen to be using Template-Driven forms and you have something like this in your component: @ViewChild('myForm') myform: NgForm;

    I've found that the markAsPristine() is a function on the form property of your form. So it would be this.myform.form.markAsPristine().

    Just thought I'd add this in case others come across markAsPristine() as not being defined.

    0 讨论(0)
  • 2021-01-31 08:01

    At the moment I can suggest two possible solutions. First one is really close to what you've suggested, as form's reset method has following signature and accepts form value as a first argument:

    //@angular/forms/src/model.d.ts:
    reset(value?: any, {onlySelf}?: { onlySelf?: boolean; }): void;
    

    In the submit handler, we will capture a copy of the last state:

    const { myForm: { value: formValueSnap } } = this;
    

    And do the reset itself:

    this.myForm.reset(formValueSnap, false);
    

    Another option from the times, when there was no possibility to reset form, is to create a helper method, which will mark each control as pristine and will keep the data. It can be called in the same submit helper in place of the resetting.

    private _markFormPristine(form: FormGroup | NgForm): void {
        Object.keys(form.controls).forEach(control => {
            form.controls[control].markAsPristine();
        });
    }
    

    Link to the updated plunkr.

    0 讨论(0)
提交回复
热议问题