我的页面上有一个表单,当我调用 FormGroup.reset()
时,它会将表单类设置为 ng-pristine ng-untouched
但 FormControl.hasError(...)
仍然返回真值。我在这里做错了什么?
模板
<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
<mat-form-field>
<input matInput formControlName="email" />
<mat-error *ngIf="email.hasError('required')">
Email is a required feild
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" formControlName="password" />
<mat-error *ngIf="password.hasError('required')">
Password is a required feild
</mat-error>
</mat-form-field>
<button type="submit">Login</button>
</form>
零件
export class MyComponent {
private myForm: FormGroup;
private email: FormControl = new FormContorl('', Validators.required);
private password: FormControl = new FormControl('', Validators.required);
constructor(
private formBuilder: FormBuilder
) {
this.myForm = formBuilder.group({
email: this.email,
password: this.password
});
}
private submitForm(formData: any): void {
this.myForm.reset();
}
}
普朗克
https://embed.plnkr.co/Hlivn4/
原文由 efarley 发布,翻译遵循 CC BY-SA 4.0 许可协议
它(
FormGroup
)行为正确。您的表单需要用户名和密码,因此当您重置表单时它应该是无效的(即没有用户名/密码的表单是无效的)。如果我理解正确,您的问题是为什么在您第一次加载页面时没有出现红色错误(表单也无效),但是当您单击按钮时会弹出。当您使用 Material 时,这个问题尤为突出。
AFAIK,
<mat-error>
check the validity ofFormGroupDirective
, notFormGroup
, andFormGroup
does not resetFormGroupDirective
.这有点不方便,但要清除<mat-error>
您还需要重置FormGroupDirective
。为此,在您的模板中,定义一个变量,如下所示:
在您的组件类中,调用
formDirective.resetForm()
:GitHub问题: https ://github.com/angular/material2/issues/4190