遍历嵌套的表单组,如果每个表单控件都有模式错误,则将其更改为null [英] Loop through nested formgroup and change each form control value to null if it has pattern error

查看:116
本文介绍了遍历嵌套的表单组,如果每个表单控件都有模式错误,则将其更改为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须查找我的formcontrol之一是否有模式错误.如果它有模式错误,那么我必须将该formcontrol的值更改为null.

我写了一个递归方法,该方法调用自身以检查表单控件是否存在模式错误,然后最终返回true或false,但是我想要的是将该formcontrol的值更改为null

这是我的递归函数,

  hasPatternError(form:AbstractControl,isRecursion = false):布尔值{如果(!isRecursion){this.patternErrors = [];}if(form instanceof FormControl){返回form.hasError('pattern')=== true ??无效的;}if(form instanceof FormArray){形式?.controls?.forEach(e => {this.hasAnyPatternError(e,true);});}if(form instanceof FormGroup){Object.keys(form.controls).forEach(key => {const错误= this.hasAnyPatternError(form.get(key),true);如果(错误===真){this.patternErrors.push(error);}});返回this.patternErrors.length>0?真假;}} 

这是我的表单,正在监听值更改事件.对于change事件,我正在调用上面的递归方法,以查找任何表单控件是否存在模式错误,但坚持将该表单控件的值更改为null.

注意:我希望方法(hasPatternError)返回一个对象(该对象的错误已转换为null,并且不希望表单实时更改)

  ngOnInit(){this.myForm = this.fb.group({姓名: [''],地址:this.fb.group({街道: [''],压缩: [''],licenseNo:['',[Validators.required,Validators.pattern(/^ [a-z0-9] {10} $/i)]]],})})this.myForm.valueChanges.subscribe(数据=>{console.log(this.hasAnyPatternError(this.myForm))});} 

这是我的代码在stackblitz上

解决方案

按下错误时,您已经引用了 form 和控件 key .

此时在控件上设置值.

  • 由于您是通过递归进行的,因此似乎有些奇怪我在您的堆叠中玩它时的行为.
  • 但是我想说的是,控件上有一个 setValue 函数,只需要确定在您的逻辑中使用它的最佳方法.
  • 甚至可能需要探索消除弹跳的行为等,以使用户有时间完成击键.

  if(!form.controls [key] ['controls']&& error === true){setTimeout(()=> {form.controls [key] .setValue('');},3000)this.patternErrors.push(error);} 

我添加了一个 setTimeout ,等待3秒钟,然后将值设置回''以模拟去抖动...似乎有效,但这不是正确的解决方案,仅说明您需要探索的原理以在递归中正确利用 setValue .

STACKBLITZ

https://stackblitz.com/edit/ng-nested-formgroup-zet7ry?file = src/app/app.component.ts

I have to find if one of my formcontrols has a pattern error. If it has a pattern error, then I have to change the value of that formcontrol to null.

I wrote a recursive method that calls itself to check if one f the form control has a pattern error and then it finally returns true or false, But what I want is to change the value of that formcontrol to null

Here is my recursive function,

hasPatternError(form: AbstractControl, isRecursion = false): boolean {
        if (!isRecursion) {
            this.patternErrors = [];
        }
        if (form instanceof FormControl) {
            return form.hasError('pattern') === true ?? null;
        }
        if (form instanceof FormArray) {
            form?.controls?.forEach(e => {
                this.hasAnyPatternError(e, true);
            });
        }
        if (form instanceof FormGroup) {
            Object.keys(form.controls).forEach(key => {
                const error = this.hasAnyPatternError(form.get(key), true);
                if (error === true) {
                    this.patternErrors.push(error);
                }
            });
            return this.patternErrors.length > 0 ? true : false;
        }
}

This is my form, listening to value changes event. On the change event, I am calling the above recursive method to find if any of the form control has a pattern error but stuck on changing the value of that formcontrol to null.

Note: I want the method (hasPatternError) to return an object(that has error converted to null and not expecting the form to change realtime)

ngOnInit() {
    this.myForm = this.fb.group({
      name: [''],
      address: this.fb.group({
        street: [''],
        zip: [''],
        licenseNo: ['', [Validators.required, Validators.pattern(/^[a-z0-9]{10}$/i)]],
      })
    })
    this.myForm.valueChanges.subscribe(
      data => {
        console.log(this.hasAnyPatternError(this.myForm))
      }
    );
  }

Here is my code on stackblitz

解决方案

You already have reference to the form and the control key when you push the error.

Set the value on the control at that time.

  • Because you are doing this with recursion, it seems to have some odd behavior when I played with it in your stackblitz.
  • But the point I wanted to make is that there is a setValue function on the control for this, just need to determine the best way to use it in your logic.
  • Might even need to explore debouncing the behavior etc to allow the user time to finish key strokes.

if (!form.controls[key]['controls'] && error === true) {
                    setTimeout(()=>{
                      form.controls[key].setValue('');
                    },3000)
                    this.patternErrors.push(error);
                }

I added a setTimeout to wait 3 seconds before setting value back to '' to simulate debounce... it appears to work, but this is not a proper solution, just illustrates the principal you need to explore to leverage setValue properly in your recursion.

STACKBLITZ

https://stackblitz.com/edit/ng-nested-formgroup-zet7ry?file=src/app/app.component.ts

这篇关于遍历嵌套的表单组,如果每个表单控件都有模式错误,则将其更改为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆