当用户提交当前值时,我正在尽可能快地为值服务。在本例中,在提交当前值之后,我将重置表单并向用户提供新值。在提供新值之后,async调用form.reset执行就完成了,所以最后我的用户获得了空/空值。
是否有其他方法来实现这一目标,或者是否有机会使其成为sync?
代码:.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>我期待的是在单击Done按钮后,我需要在文本字段中显示“角5”,但它显示为空。
有没有人能解释为什么这里没有变化检测?
发布于 2018-06-12 07:31:21
我发现使用ChangeDetectorRef,它的工作就像一个魅力!
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();
}
}发布于 2018-06-12 07:31:33
你可以用,
onSubmit(){
this.form.form.markAsPristine();
this.form.form.markAsUntouched();
this.form.form.updateValueAndValidity();
}这里是代码:
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();
}
}发布于 2018-06-12 06:38:13
更新onSubmit方法如下:
onSubmit(){
this.form.reset();
setTimeout(() => {
this.InitialCall();
}, 1)
}您必须使用setTimeout
https://stackoverflow.com/questions/50810561
复制相似问题