Resetting a form in Angular 2 after submit

前端 未结 12 1972
悲哀的现实
悲哀的现实 2020-12-01 03:16

I am aware that Angular 2 currently lacks a way to easily reset a form to a pristine state. Poking around I have found a solution like the one below that resets the form f

12条回答
  •  我在风中等你
    2020-12-01 03:56

    I used in similar case the answer from Günter Zöchbauer, and it was perfect to me, moving the form creation to a function and calling it from ngOnInit().

    For illustration, that's how I made it, including the fields initialization:

    ngOnInit() {
        // initializing the form model here
        this.createForm();
    }
    
    createForm() {
        let EMAIL_REGEXP = /^[^@]+@([^@\.]+\.)+[^@\.]+$/i; // here just to add something more, useful too
    
        this.userForm = new FormGroup({
            name: new FormControl('', [Validators.required, Validators.minLength(3)]),
            city: new FormControl(''),
            email: new FormControl(null, Validators.pattern(EMAIL_REGEXP))
        });
    
        this.initializeFormValues();
    }
    
    initializeFormValues() {
        const people = {
            name: '',
            city: 'Rio de Janeiro',  // Only for demonstration
            email: ''
        };
        (this.userForm).setValue(people, { onlySelf: true });
    }
    
    resetForm() {
        this.createForm();
        this.submitted = false;
    }
    

    I added a button to the form for a smart reset (with the fields initialization):

    In the HTML file (or inline template):

    
    

    After loading the form at first time or after clicking the reset button we have the following status:

    FORM pristine: true 
    FORM valid: false (because I have required a field) 
    FORM submitted: false
    Name pristine: true
    City pristine: true
    Email pristine: true
    

    And all the field initializations that a simple form.reset() doesn't make for us! :-)

提交回复
热议问题