不能选择需要的垫子选择

时间:2018-11-28 15:01:27

标签: angular angular-material

使用mat-select作为唯一必填字段的每个formGroup不能通过FormGroup.reset()进行重置,因为验证器不会重置

https://stackblitz.com/edit/material7-template-matselect-required?file=src%2Fapp%2Fapp.component.html

提交时,第一个字段为空并标记为错误...

对我来说唯一有效的解决方案是使用ngIf来重新生成表单,但对于看到空html几秒钟的用户而言,这并不是一个很好的选择。

还有其他解决方案吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

由于已经有了一个可以接受的答案,所以我可以在这里建议增加一些内容。

这是Material的一个鲜为人知的错误,作为一种解决方法,您可以将ElementReference添加到form标签#f="ngForm"中:

<form [formGroup]="quickFileForm" (ngSubmit)="saveQuickFileForm()" #f="ngForm">

然后在您的TS部分添加一个@ViewChild装饰器,该装饰器引用表单中的标记:

import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  group = new FormGroup({
    select: new FormControl(null, Validators.required),
    input: new FormControl()
  });

  @ViewChild('f') myForm;

   ....
   ....
}

不要忘记从@angular/core上方导入它。然后只需添加:

this.myForm.resetForm();

使用您的方法:

submit() {
    if(this.group.valid) {
      const obj = new MyObj();
      Object.assign(obj, this.group.value);

      this.survey.push(obj);
      this.myForm.resetForm(); // <-- Here you add it.
      return;
    }

    alert('not valid, try again')
  }

答案 1 :(得分:0)

使用SetValidators将验证器设置为nullvalidator

  this.group.controls['select'].setValidators([Validators.nullValidator])
  this.group.controls['select'].updateValueAndValidity();
相关问题