Angular 5中的表单重置功能 [英] Form reset functionality in angular 5
问题描述
当用户提交当前值时,我会尽快提供价值.在这种情况下,提交当前值后,我将重置表单并将新值提供给用户.它作为async
调用form.reset
的执行工作在提供新值后完成,因此最终我的用户获得了null/empty值.
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
代码:
.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
按钮后,我需要在文本字段中显示"Angular 5",但它显示为空.
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 ?
推荐答案
>, 就像魅力一样!
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();
}
}
这篇关于Angular 5中的表单重置功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!