[英]Form reset functionality in angular 5
當用戶提交當前值時,我盡可能快地提供價值。 在這種情況下,在提交當前值后,我正在重置表單並向用戶提供新值。 它作為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
}
.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',但它顯示為空。
任何人都可以解釋為什么變化檢測不會發生在這里?
您可以使用,
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();
}
}
我發現使用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();
}
}
將onSubmit
方法更新為:
onSubmit(){
this.form.reset();
setTimeout(() => {
this.InitialCall();
}, 1)
}
您將不得不使用setTimeout
您應該對表單使用反應式表單方法,因為這很容易維護表單的驗證和控制。 通過使用反應形式方法,您可以使用patchValue或setValue方法的反應形式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.