angular5 – mat-select必需的验证不起作用

前端之家收集整理的这篇文章主要介绍了angular5 – mat-select必需的验证不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码

<form #createForm="ngForm">
 <mat-form-field>
   <mat-select placeholder="Favorite food"
      matInput
     [ngModel]
     food="food"
     #food="ngModel" required>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{ food.viewValue }}
    </mat-option>
   </mat-select>
</mat-form-field>
</form>
<button [disabled]="!createForm.valid">submit</button>

由于我希望“选择”是必填字段,因此在呈现表单时应禁用“提交”按钮.但是,显示表单时会启用“提交”按钮.问题是什么?

解决方法

用于验证角度5使用反应形式. refer this

*** componentsnet.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])
 });
}
}

**** Component.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.

猜你在找的Angularjs相关文章