Form reset functionality in angular 5

2019-07-19 23:41发布

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 ?

标签: angular forms
4条回答
等我变得足够好
2楼-- · 2019-07-20 00:19

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.

查看更多
Anthone
3楼-- · 2019-07-20 00:23

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(); 
  }
}
查看更多
▲ chillily
4楼-- · 2019-07-20 00:29

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

查看更多
地球回转人心会变
5楼-- · 2019-07-20 00:35

Update onSubmit method as:

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

You will have to use setTimeout

查看更多
登录 后发表回答