对于 Angular 5 中的验证,请使用反应形式。参考这个
*** componenet.ts *******
import { FormControl, Validators, FormBuilder, FormGroup, ReactiveFormsModule, NgForm } from '@angular/forms';
export class Test implements OnInit{
foodform:FormGroup;
constructor(){}
ngOnInit() {
// create form group of controls
this.foodform = new FormGroup({
favoriteFood: new FormControl('', [Validators.required])
});
}
}
**** 组件.html************
<form #createForm="ngForm" [formGroup]="foodform ">
<mat-form-field>
<mat-select placeholder="Favorite food"
matInput
[ngModel]
food="food"
#food="ngModel" formControlName="favoriteFood">
<mat-option *ngFor="let food of foods" [value]="food.value" >
{{ food.viewValue }}
</mat-option>
</mat-select>
<mat-error *ngIf="foodform.controls['favoriteFood'].hasError('required') && foodform.controls['favoriteFood'].pristine">
Required Message
</mat-error>
</mat-form-field>
</form>
在您的 html 表单中使用[formGroup]
和。formControlName