我有以下表格:
<form [formGroup]="claimForm">
<header class="card-header bg-red">
<h2>Repairer Information</h2>
</header>
<div class="card-body p-3">
<div class="tab-content pb-4" id="myTabContent">
<div class="row my-4">
<div class="form-group col-sm-6">
<label for="repairerName">Repairer Contact Name</label>
<input matInput class="form-control" formControlName="repairerName"
[(ngModel)]="repairerName">
</div>
<div class="form-group col-sm-6">
<label for="repairerEmail">Repairer Email Address</label>
<input matInput class="form-control"
placeholder="Ex. pat@example.com"
formControlName="emailValidator"
[formControl]="f.emailFormControl"
[errorStateMatcher]="matcher"
[(ngModel)]="repairerEmail">
<mat-error *ngIf="f.emailValidator.hasError('email') && !f.emailValidator.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="f.emailValidator.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</div>
</div>
<button class="btn btn-icon btn-secondary" [routerLink]="['/claims/create/2']">
<i class="material-icons">check_circle_outline</i><span>Continue</span>
</button>
</div>
</div>
</form>
这是我的 .ts 文件:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
@Component({
selector: 'app-info',
templateUrl: './repairer-info.component.html',
styleUrls: ['./repairer-info.component.scss'],
animations: [BottomToUpAnimation()]
})
export class InfoComponent implements OnInit {
repairerEmail = '';
submitted = false;
// Form information
claimForm: FormGroup;
matcher = new MyErrorStateMatcher();
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.claimForm = this.formBuilder.group({
emailValidator: [ this.repairerEmail, [Validators.required, Validators.email] ]
});
}
// convenience getter for easy access to form fields
get f() { return this.claimForm.controls; }
}
我使用了此链接中的代码。
因为它应该可以工作,当您使用输入或提交进行一些交互时,它会说电子邮件是强制性的。但我的错误信息总是被显示:
我做错了什么?为什么required
即使我没有对我的输入做任何事情,属性的错误消息也会一直显示?
编辑:我试图删除占位符或将其设置为有效值,但错误仍然存在。尝试删除 ngModel 时也会发生同样的情况。