[英]How can I reset a reactive form control to originate state?
嗨,我需要有关反应式表单元素的帮助。 基本上,它是必需的元素。 当视图第一次加载时,元素不是红色的(没有显示它需要一个值的错误)。 这很好,如果我点击里面然后导航离开而不填写它,它只会显示红色。 我目前的逻辑是,当我填写并提交表单时……表单数据被提交,但我仍然在同一页面上,但所有以前的值都被删除了。 问题是......现在表单元素认为我没有填写它并且在它不应该抱怨时抱怨,因为从技术上讲它是一个新表格。
这是我的表单组:
this.transactionForm = fb.group({
'billNumber': [null, Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9\\-_]*$'), Validators.maxLength(30)])],
'birthdate': [null, Validators.required],
'transactionDate': [new Date(), Validators.required],
'type': ['Sales', Validators.required],
});
目前,我有一个名为 reset() 的函数,我在提交表单时调用它:
reset() {
this.transactionForm.get('billNumber').setErrors({required: false});
this.transactionForm.controls['billNumber'].setValue('');
this.transactionForm.controls['billNumber'].setErrors({'incorrect': false});
this.transactionForm.controls['billNumber'].markAsUntouched();
this.transactionForm.controls['billNumber'].markAsPristine();
this.transactionForm.controls['birthdate'].setValue(null);
this.transactionForm.controls['birthdate'].markAsUntouched();
this.transactionForm.controls['birthdate'].markAsPristine();
this.transactionForm.controls['birthdate'].setErrors({'incorrect': false});
this.transactionForm.controls['transactionDate'].setValue(new Date());
this.transactionForm.controls['type'].setValue('Sales');
this.transactionForm.clearValidators();
}
将 type 和 transactionDate 重置为默认值更容易,但我不确定我可以对上面的生日或账单编号做些什么。 我尝试了上面的代码,但在重置时,控件仍然是红色的(并且无效)......它应该处于新的/原始状态。 我怎样才能解决这个问题?
使用reset('')
并通过markAsPristine()
将整个表单组设置为pristine
markAsPristine()
应该可以解决问题
在 Angular 中重置表单
方法#1(❌不推荐)
HTML:
<button type="reset" >Clear Form </button>
方法#2(✅首选)
打字稿:
fg = new FormGroup({name:new FormControl(''),
nestedFg : new FormGroup({abc : new FormControl('')})
})
fg.reset() // formGroup reset
fg.get('name').reset() // formControl reset
fg.get('nestedFg').reset() // Nested formGroup reset
fg.get('nestedFg').get('abc').reset() // Nested formControl reset
方法 #1 注意:有必要提及不要使用此方法,因为类型重置应避免按照 mozilla 文档使用以获取更多信息
方法#2:对表单给予更多控制使用 formGroup 给予更多控制
以上答案都不适合我,所以我意识到它必须通过将材料元素用于表单组控件来做一些事情。
我发现了这个错误: https : //github.com/angular/material2/issues/4190
添加这样的东西为我修复了它:
@ViewChild(FormGroupDirective) myForm;
sendDataToBackendAndResetForm() {
// TODO: send data to backend
if (this.myForm) {
this.myForm.resetForm();
}
}
我不明白为什么在我传递了一个空字符串之前重置对我不起作用。 我想重置一个特定的控件。 Form 是用 formbuilder 和 Angular 8 构建的。
做了类似this.transactionForm.get('billNumber').reset('')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.