我的预期结果是在提交表单后重置表单并将其默认值绑定到formGroup控件。我通过调用表单提交上的reset()提交后,尝试将表单重置为其默认数据。请告诉我如何重置日期和时间字段中的默认值。
示例:
pickupDate = new Date().toISOString().slice(0,10);
pickupTime = moment().format() ;
onSubmit(orderData: Order){
this.apiService(orderData).subscribe( order => {
orderForm.reset()
})
}
请帮忙谢谢
提交表格后。你在打电话
this.yourForm.reset()
然后,您可以像这样将初始值修补到表单。
this.yourForm.patchValue({
firstControllerName: this.initialValues.value1,
secondControllerName: this.initialValues.value2,
// other controller names goes here
});
希望这可以帮助。
我不知道你的formBuilder是怎么样的,但是
this.yourForm.reset({})已经完成了清空未预定字段的技巧。你可以尝试类似的东西......
ngOnChanges() {
this.queryForm.reset({
});
// We generate an empty form again.
this.createForm();
}
而你的createForm看起来像这样......
createForm() {
// As the method name suggests, we create a form. A form consists of Groups, Controls - and optionally - Arrays...
this.queryForm = new FormGroup({
query: new FormControl(''),
formArray: new FormArray([this.initQueryConditions())
})
}
清除方法取决于您使用的是模板驱动表单还是反应表单。
Angular Forms, check full syntax with explaination
如果是模板,则需要将模型对象设置为默认值(不一定是空的)。如果是被动的,那么调用一个明确清空每个形式值的方法。
之后,执行form.Reset将其移回“pristine | unchanged”状态,从而删除验证器
您可以同时重置和设置所需的默认值,如下所示:
defaultFormValues: any = {
date: Date.now
};
formG: FormGroup = new FormGroup({
'date': new FormControl(this.defaultFormValues.date)
});
onSubmit(orderData: Order) {
this.apiService(orderData).subscribe(order => {
this.formG.reset(this.defaultFormValues);
});
}