首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >形复位功能(角5)

形复位功能(角5)
EN

Stack Overflow用户
提问于 2018-06-12 06:29:40
回答 4查看 6.3K关注 0票数 2

当用户提交当前值时,我正在尽可能快地为值服务。在本例中,在提交当前值之后,我将重置表单并向用户提供新值。在提供新值之后,async调用form.reset执行就完成了,所以最后我的用户获得了空/空值。

是否有其他方法来实现这一目标,或者是否有机会使其成为sync

代码:.ts

代码语言:javascript
复制
     @ViewChild('f') form

     ngOnInit() {
       this.initialCall();
     }

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

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

.html

代码语言:javascript
复制
<form  #f="ngForm"  (ngSubmit)="onSubmit(f.value)">
  <label>Name</label>
  <input type="text" [(ngModel)]="name" name="initail">
  <button type="submit">Done</button>
</form>

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

有没有人能解释为什么这里没有变化检测?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-06-12 07:31:21

我发现使用ChangeDetectorRef,它的工作就像一个魅力!

代码语言:javascript
复制
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(); 
  }
}
票数 3
EN

Stack Overflow用户

发布于 2018-06-12 07:31:33

你可以用,

代码语言:javascript
复制
onSubmit(){
    this.form.form.markAsPristine();
    this.form.form.markAsUntouched();
    this.form.form.updateValueAndValidity();
}

这里是代码:

代码语言:javascript
复制
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(); 
  }
}

这是一个演示

票数 5
EN

Stack Overflow用户

发布于 2018-06-12 06:38:13

更新onSubmit方法如下:

代码语言:javascript
复制
onSubmit(){
    this.form.reset();
    setTimeout(() => {
      this.InitialCall(); 
    }, 1)
}

您必须使用setTimeout

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50810561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档