Resetting a form in Angular 2 after submit

前端 未结 12 1952
悲哀的现实
悲哀的现实 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:57

    >= RC.6

    Support resetting forms and maintain a submitted state.

    console.log(this.form.submitted);
    
    this.form.reset()
    

    or

    this.form = new FormGroup()...;
    

    importat update

    To set the Form controls to a state when the form is created, like validators, some additional measurements are necessary

    In the view part of the form (html) add an *ngIf to show or hide the form

    <form *ngIf="showForm"
    

    In the component side of the form (*.ts) do this

      showForm:boolean = true;
    
      onSubmit(value:any):void {
        this.showForm = false;
        setTimeout(() => {
        this.reset()
          this.showForm = true;
        });
      }
    

    Here is a more detailed example:

    export class CreateParkingComponent implements OnInit {
      createParkingForm: FormGroup ;
      showForm = true ;
    
      constructor(
        private formBuilder: FormBuilder,
        private parkingService: ParkingService,
        private snackBar: MatSnackBar) {
    
          this.prepareForm() ;
      }
    
      prepareForm() {
        this.createParkingForm = this.formBuilder.group({
          'name': ['', Validators.compose([Validators.required, Validators.minLength(5)])],
          'company': ['', Validators.minLength(5)],
          'city': ['', Validators.required],
          'address': ['', Validators.compose([Validators.required, Validators.minLength(10)])],
          'latitude': [''],
          'longitude': [''],
          'phone': ['', Validators.compose([Validators.required, Validators.minLength(7)])],
          'pictureUrl': [''],
          // process the 3 input values of the maxCapacity'
          'pricingText': ['', Validators.compose([Validators.required, Validators.minLength(10)])],
          'ceilingType': ['', Validators.required],
        });
      }
    
      ngOnInit() {
      }
    
    
      resetForm(form: FormGroup) {
        this.prepareForm();
      }
    
      createParkingSubmit() {
        // Hide the form while the submit is done
        this.showForm = false ;
    
        // In this case call the backend and react to the success or fail answer
    
        this.parkingService.create(p).subscribe(
          response => {
            console.log(response);
            this.snackBar.open('Parqueadero creado', 'X', {duration: 3000});
            setTimeout(() => {
              //reset the form and show it again
              this.prepareForm();
                this.showForm = true;
              });
          }
          , error => {
            console.log(error);
            this.showForm = true ;
            this.snackBar.open('ERROR: al crear Parqueadero:' + error.message);
          }
          );
      }
    }
    

    Plunker example

    original <= RC.5 Just move the code that creates the form to a method and call it again after you handled submit:

    @Component({
      selector: 'form-component',
      template: `
        <form (ngSubmit)="onSubmit($event)" [ngFormModel]="form">
           <input type="test" ngControl="name">
           <input type="test" ngControl="email">
           <input type="test" ngControl="username">
           <button type="submit">submit</button>
        </form>
        <div>name: {{name.value}}</div>
        <div>email: {{email.value}}</div>
        <div>username: {{username.value}}</div>
    `
    })
    class FormComponent {
    
      name:Control;
      username:Control;
      email:Control;
    
      form:ControlGroup;
    
      constructor(private builder:FormBuilder) {
        this.createForm();
      }
    
      createForm() {
        this.name = new Control('', Validators.required);
        this.email = new Control('', Validators.required);
        this.username = new Control('', Validators.required);
    
        this.form = this.builder.group({
          name: this.name,
          email: this.email,
          username: this.username
        });
      }
    
      onSubmit(value:any):void {
        // code that happens when form is submitted
        // then reset the form
        this.reset();
      }
    
      reset() {
        this.createForm();
      }
    }
    

    Plunker example

    0 讨论(0)
  • 2020-12-01 03:57

    Use NgForm's .resetForm() rather than .reset() because it is the method that is officially documented in NgForm's public api. (Ref [1])

    <form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm">
    

    The .resetForm() method will reset the NgForm's FormGroup and set it's submit flag to false (See [2]).

    Tested in @angular versions 2.4.8 and 4.0.0-rc3

    0 讨论(0)
  • 2020-12-01 03:57

    For Angular 2 Final, we now have a new API that cleanly resets the form:

    @Component({...})
    class App {
    
        form: FormGroup;
         ...
        reset() {
           this.form.reset();
       }
    }
    

    This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.

    0 讨论(0)
  • 2020-12-01 03:57

    if anybody wants to clear out only a particular form control one can use

    formSubmit(){
    this.formName.patchValue({
             formControlName:''
              //or if one wants to change formControl to a different value on submit
              formControlName:'form value after submission'     
        });
    }
    
    0 讨论(0)
  • 2020-12-01 04:03
    form: NgForm;
    
    form.reset()
    

    This didn't work for me. It cleared the values but the controls raised an error.

    But what worked for me was creating a hidden reset button and clicking the button when we want to clear the form.

    <button class="d-none" type="reset" #btnReset>Reset</button>
    

    And on the component, define the ViewChild and reference it in code.

    @ViewChild('btnReset') btnReset: ElementRef<HTMLElement>;
    

    Use this to reset the form.

    this.btnReset.nativeElement.click();
    

    Notice that the class d-none sets display: none; on the button.

    0 讨论(0)
  • 2020-12-01 04:06

    I'm using reactive forms in angular 4 and this approach works for me:

        this.profileEditForm.reset(this.profileEditForm.value);
    

    see reset the form flags in the Fundamentals doc

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