angular - 具有自定义验证的角度材料自定义表单控件组件不会在表单提交时触发
问题描述
我已经实现了一个带有自定义验证的自定义表单控件,但是一旦提交父表单,我就无法将控件标记为无效我希望当用户按下提交时,控件会失效.. 到目前为止,只有在触摸它时它才会失效.. 在我的 onDoCheck 中,我设法读取了 form.isSubmitted 属性,但我注意到该控件仍被标记为“有效”
即使我构建逻辑并在我的 onDoChek 中将其强制为无效.. 这样在提交时的父组件中我无法检查控件的有效性,因为我会在 onSubmit 回调之后设置它.. 我在这里缺少什么?
我能想到的丑陋修复是添加
this.form.get('test').updateValueAndValidity();
this.form.get('test').markAsTouched();
在 onSubmit 回调上,但不这样做不应该开箱即用吗?
这里是stackblitz: https ://stackblitz.com/edit/angular-k5un7v?file=src%2Fapp%2Fcustom-input%2Fcustom-input.component.ts
任何帮助是极大的赞赏
解决方案
对于那些感兴趣的人,我找到了一个更好的解决方案,我不需要弄乱父组件中的表单
https://stackblitz.com/edit/angular-7gmzya?file=src%2Fapp%2Fcustom-input%2Fcustom-input.component.ts
基本上我所要做的就是
ngAfterViewInit() {
//console.log("IS REQUIRED? ", this.required)
if (this.required && this.ngControl && this.ngControl.control) {
this.ngControl.control.setValidators(this.validate);
//UPDATING VALIDITY:
setTimeout(()=> {
this.ngControl.control.updateValueAndValidity();
}
);
}
}
在 ngDoCheck 中:
this.errorState = this.ngControl.invalid && (this.ngControl.touched);
就是现在:
this.errorState = this.ngControl.invalid && (this.ngControl.touched || this.form.submitted);
这样组件的行为就像一个标准的角度形式控件,但我认为它并不完美,因为我不得不求助于 setTimeout,所以如果你们有一个更优雅的解决方案,我将把它留作未解决..
推荐阅读
- wpf - WPF中没有调用按钮命令?
- angular - Angualr Webapp:从 Android 相机中选择的图像在上传时会引发 CORS 错误。相同的图像上传在桌面上工作正常
- python - 无法将 librosa-module 导入 python
- c# - 使用 enter 在文本框中输入多个信息时出现问题
- laravel - Laravel Storage::从Gmail url下载不起作用
- c# - HttpClient TimeOut 和 Polly Bulkhead Policy 问题
- python - Python 模块依赖项。如何获取完整列表?
- arduino - Arduino 在 windows 和 ubuntu 上都没有连接到 Mosquitto
- python - 获取传递给 mock_open 的参数并为 mock 调用不同的函数
- c# - ASP .Net Web API 中未触发异常过滤器