Angular 5中的表单重置功能

k11*_*1k2 2 forms angular

用户提交当前值时,我会尽快提供价值。在这种情况下,提交当前值后,我将重置表单并向用户提供新值。它在提供新值后完成了async调用form.reset执行,因此最终我的用户获得了null / empty值。

是否有其他替代方法可以实现这一目标,或者有任何实现的机会 sync

码: .ts

     @ViewChild('f') form

     ngOnInit() {
       this.initialCall();
     }

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

     onSubmit(){
       this.form.reset(); //reset form
       this.initialCall(); //serve next value
     }
Run Code Online (Sandbox Code Playgroud)

.html

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

我期望的是单击Done按钮后,我需要在文本字段中显示“ Angular 5”,但它显示为空。

有人能解释为什么没有在这里进行变更检测吗?

Sra*_*van 5

您可以使用,

onSubmit(){
    this.form.form.markAsPristine();
    this.form.form.markAsUntouched();
    this.form.form.updateValueAndValidity();
}
Run Code Online (Sandbox Code Playgroud)

这是代码:

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(); 
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示