Angular 5资料:下拉(选择)所需的验证不起作用 [英] Angular 5 material: dropdown (select) required validation is not working

查看:98
本文介绍了Angular 5资料:下拉(选择)所需的验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ngForm中有一个材料下拉列表,当我按要求设置此选择时,它旁边会显示一个星号*,但如果我未从下拉列表中选择任何选项,则该表单被视为有效.

I have a material dropdown inside my ngForm, when I set this select as required it shows an asterisk * beside it but the form is seen as valid if I don't select any option from the dropdown.

<mat-form-field class="col-4 offset-1">
<mat-select placeholder="Some placeholder" [(value)]="data.name" required>
  <mat-option *ngFor="let name of names" [value]="name.value">
    name.viewValue
  </mat-option>
</mat-select>
</mat-form-field>

这与将物料输入设置为required时发生的情况不同,如果输入为空,则会使表单无效.

This is unlike what happens if I set the material input to required which will make the form invalid if it is empty.

<mat-form-field class="col-4 offset-1">
 <input matInput name="dob" placeholder="Date Of Birth" [(ngModel)]="data.dob" required>
  </mat-form-field>

我更喜欢使用模板驱动的方法来解决此问题,而不是使用ReactiveForms(我发现了一些有关ReactiveForms的解决方案),有人可以帮助我吗?

I prefer to solve this using a template driven approach not by using ReactiveForms ( I found some solution talking about the ReactiveForms), can anyone help me?

注意:

我发现了一个标题相似的问题,但它正在使用FormGroup(reactiveForms)

I found a question of similar title but it is using FormGroup (reactiveForms)

我在 stackblitz中举了一个例子来说明

推荐答案

您将required添加到了选择的option中,而不是select中.这样做:

You added required to the select's option, not the select. Do it like:

<mat-form-field>
  <mat-select placeholder="Favorite food" name="select" [(ngModel)]="select" required>
    <mat-option *ngFor="let food of foods" [value]="food.value" >
      {{ food.viewValue }}
    </mat-option>
  </mat-select>
</mat-form-field>

演示

这篇关于Angular 5资料:下拉(选择)所需的验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆