[英]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.