代码之家  ›  专栏  ›  技术社区  ›  Pablo De Luca

角度材质2-手动将字段/控件设置为无效

  •  0
  • Pablo De Luca  · 技术社区  · 6 年前

    我正在做一个嵌套的反应式表单。有一个 open issue 关于在表单控件位于不同组件中时自动设置将字段标记为无效(红色)的类。

    这些课程是 mat-form-field-invalid mat-input-invalid

    因此,我解决这个问题的想法是在单击submit按钮后从FormGroup中获取无效控件,并在循环中将其与无效控件/字段的formControlName匹配 并通过编程将其设置为无效

    我试过了 formData.form.controls['formControlName'].markAsTouched(); 以及我在这里找到的其他类似的“解决方案”和谷歌搜索,但其中任何一个都有效。

    我该怎么做?

    我用的是角材料5.2.4。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Pablo De Luca    6 年前

    最后,我如何将CSS错误类添加到嵌套反应式表单中无效的字段中:

     this.invalidControls(this.formGroup); //Call it just after submit the form
    
     //The implementation of the function
     invalidControls(name): void {
        for (const field in name.controls) {
          const control = name.get(field);
    
          if(control.constructor.name == "FormArray" || control.constructor.name == "FormGroup"){
            this.invalidControls(control); //If the AbstractControl is not a FormControl the funtion will be called again
          }
          else{
            if(control.status === "INVALID"){
              control.markAsTouched({ onlySelf: true });
              control.markAsDirty({ onlySelf: true });
            }
          }
        }
      }
    

    因此,如果将控件设置为 无效的 ,则, 肮脏的 ,它是 空的 ,将添加CSS错误类。否则不会。