首页 > 解决方案 > 具有自定义验证的角度材料自定义表单控件组件不会在表单提交时触发

问题描述

我已经实现了一个带有自定义验证的自定义表单控件,但是一旦提交父表单,我就无法将控件标记为无效我希望当用户按下提交时,控件会失效.. 到目前为止,只有在触摸它时它才会失效.. 在我的 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

任何帮助是极大的赞赏

标签: angularformsvalidationangular-materialcontrolvalueaccessor

解决方案


对于那些感兴趣的人,我找到了一个更好的解决方案,我不需要弄乱父组件中的表单

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,所以如果你们有一个更优雅的解决方案,我将把它留作未解决..


推荐阅读