我的角度应用程序中有一个表单可以登录。我正在尝试显示表单验证错误,但是除非将它们放置在<mat-form-field>
之外,否则它们不会显示。
我已尝试按照here的说明添加ErrorStateMatcher
,但是它不起作用。我已经复制粘贴了在应用程序的其他组件中适用于我的相同表单结构。在这里:
<form [formGroup]="loginForm" #formDir="ngForm">
<mat-form-field>
<input [errorStateMatcher]="matcher" autocomplete="off" matInput placeholder="Email"
formControlName="username" name="username">
<mat-icon matSuffix>alternate_email</mat-icon>
<mat-error *ngIf="loginForm.controls['username'].hasError('required')">
* This field is required
</mat-error>
</mat-form-field>
<mat-form-field>
<input [errorStateMatcher]="matcher" autocomplete="off" matInput placeholder="Password"
formControlName="password" type="password" name="password" autocomplete>
<mat-icon matSuffix>vpn_key</mat-icon>
<mat-error *ngIf="loginForm.controls['password'].hasError('required')">
* this field is required
</mat-error>
</mat-form-field>
</form>
这是我的表单实例:
constructor(private router: Router,
private fb: FormBuilder) {
this.loginForm = fb.group({
username: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required])
})
}
尽管未显示错误消息,但当它们无效时,字段变为红色(Validators.required和Validators.email似乎都起作用)。
我还试图强迫输入在提交时出错,仅出于测试目的,因为我认为这不是一个合适的解决方案,例如:
this.loginForm.controls['username'].setErrors({
required: true
})
this.loginForm.controls['password'].setErrors({
required: true
})
this.loginForm.markAllAsTouched();
this.loginForm.controls['username'].markAsTouched();
this.loginForm.controls['password'].markAsTouched();
这些是我在app.module上导入的模块:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
我想念什么?