Form reset functionality in angular 5

2019-07-19 23:34发布

问题:

I'm serving value as fast as I can when user submitted current value. In this case after submitting current value I'm resetting the form and serving new value to user. It working as async call form.reset execution completes after serving new value so at the end my user get null/empty value.

Is there any alternative ways to achieve this or any chances of making it sync

code: .ts

     @ViewChild('f') form

     ngOnInit() {
       this.initialCall();
     }

     initialCall() {
       this.name = 'Angular 5';
     }

     onSubmit(){
       this.form.reset(); //reset form
       this.initialCall(); //serve next value
     }

.html

<form  #f="ngForm"  (ngSubmit)="onSubmit(f.value)">
  <label>Name</label>
  <input type="text" [(ngModel)]="name" name="initail">
  <button type="submit">Done</button>
</form>

What I'm expecting is after click on Done button I need to show 'Angular 5' in text field but it showing empty.

And do any one can explain why change detection not happening here ?

回答1:

i found using ChangeDetectorRef, and it's work like a charm!

import { Component, OnInit, ViewChild , ChangeDetectorRef} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name: string;
  @ViewChild('f') form
  ngOnInit() {
    this.InitialCall();
  }
  constructor(private changeDetectorRef: ChangeDetectorRef){}
  InitialCall() {
    this.name = 'Angular 5';
  }

  onSubmit(){
    this.form.reset();
    this.changeDetectorRef.detectChanges();
    this.InitialCall(); 
  }
}


回答2:

You can use,

onSubmit(){
    this.form.form.markAsPristine();
    this.form.form.markAsUntouched();
    this.form.form.updateValueAndValidity();
}

Here is the code:

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  name: string;
  @ViewChild('f') form
  ngOnInit() {

    this.InitialCall();
  }
  InitialCall() {
    this.name = 'Angular 5';
  }

  onSubmit(){
    this.form.form.markAsPristine();
    this.form.form.markAsUntouched();
    this.form.form.updateValueAndValidity();

    this.InitialCall(); 
  }
}

Here is a DEMO



回答3:

Update onSubmit method as:

onSubmit(){
    this.form.reset();
    setTimeout(() => {
      this.InitialCall(); 
    }, 1)
}

You will have to use setTimeout



回答4:

You should use reactive-form approach for the form, because this is very easy to maintain validation and controls of form. And by using reactive-form approach you can use patchValue or setValue method of reactive form.



标签: angular forms