[英]How to clear an Angular reactive form input values
我有一個像這樣設置的簡單反應形式
constructor(private scheduleService: ScheduleService, fb: FormBuilder) {
this.searchForm = fb.group({
from: ["", Validators.required],
to: ["", Validators.required],
date: ["", Validators.required]
});
}
我想通過單擊調用清除 function 的按鈕來清除表單字段。我的清除 function 目前不起作用,看起來像這樣
clear() {
console.log("Reset all search form fields to null.");
this.searchForm.from = "";
this.searchForm.to = "";
this.searchForm.date = "";
}
使用 angular reactive forms 時清除表單輸入字段的正確方法是什么? 如何通過使用單個語句重置所有表單字段而不是單個字段來實現此目的?
Angular開箱即用提供了reset()方法 。 在發表您的問題之前,請先進行研究。
ngOnInit(): void {
this.searchForm = this.fb.group({
from: ['', Validators.required],
to: ['', Validators.required],
date: ['', Validators.required]
});
}
重置完整表格
resetForm() {
this.searchForm.reset();
}
重置單個字段
resetFrom() {
this.searchForm.get('from').reset();
}
用於重置一個輸入
ngOnInit(): void {
this.searchForm = this.fb.group({
from: ['', Validators.required],
to: ['', Validators.required],
date: ['', Validators.required]
});
}
方便的吸氣劑,可以輕松訪問表單字段
get f() { return this.registerForm.controls; }
重置一個字段示例(來自)
this.f.from.reset();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.