TS下
import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';
/**
* @title Input with error messages
*/
@Component({
selector: 'input-errors-example',
templateUrl: 'input-errors-example.html',
styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
}
html下
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" [formControl]="emailFormControl">
<mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>