【问题标题】:Angular material 2 - Set manually a field/control as invalidAngular material 2 - 手动将字段/控件设置为无效
【发布时间】:2018-09-25 14:30:21
【问题描述】:

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

这些类是mat-form-field-invalidmat-input-invalid

所以我解决这个问题的想法是在单击提交按钮后从 FormGroup 中获取无效控件,并在循环中将它们与无效控件/字段的 formControlName 匹配并以编程方式将它们设置为无效。

我尝试使用formData.form.controls['formControlName'].markAsTouched(); 和我在此处找到的其他类似“解决方案”并进行谷歌搜索,但其中任何一个都有效。

我该怎么做?

我正在使用 Angular Material 5.2.4。

【问题讨论】:

  • 你试过setErrors()吗?
  • @G.Tranter 是的,我试过了,但它不起作用。稍后我将用一个 WorkArround 回答一个问题

标签: angular angular-material2


【解决方案1】:

最后,我将 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 });
        }
      }
    }
  }

因此,如果您将控件设置为invaliddirty,并且它是empty,则会添加 CSS 错误类。否则不行。

【讨论】:

  • 谢谢,这是迄今为止最简单的解决方法,也适用于父组件。
  • 我看不出一点,您正在检查 control.status 是否为 INVALID,这不是已经使控件无效了吗?我有一种情况,非表单相关字段设置为无效,但FormControl 的状态字段是只读的。
猜你喜欢
  • 2017-09-19
  • 2018-03-11
  • 2018-05-15
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 2014-08-27
相关资源
最近更新 更多