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

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

问题描述

我必须找出我的表单控件之一是否存在模式错误.如果它有模式错误,那么我必须将该表单控件的值更改为 null.

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

这是我的递归函数,

hasPatternError(form: AbstractControl, isRecursion = false): boolean {如果(!isRecursion){this.patternErrors = [];}if (form instanceof FormControl) {return form.hasError('pattern') === true ??空值;}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);如果(错误 === 真){this.patternErrors.push(error);}});返回 this.patternErrors.length >0 ?真假;}}

这是我的表单,监听值变化事件.在更改事件中,我调用上述递归方法来查找是否有任何表单控件存在模式错误,但仍坚持将该表单控件的值更改为 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(数据 =>{控制台日志(this.hasAnyPatternError(this.myForm))});}

这是我的代码 在 stackblitz 上

解决方案

当你推送错误时,你已经拥有了对 form 和控件 key 的引用.>

设置当时控件上的值.

  • 因为你是用递归来做这件事的,所以似乎有些奇怪我在你的 stackblitz 中使用它时的行为.
  • 但我想说的是,控件上有一个 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天全站免登陆