Angular 5资料:下拉(选择)所需的验证不起作用 [英] Angular 5 material: dropdown (select) required validation is not working
问题描述
我的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)
推荐答案
您将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屋!