【发布时间】:2021-08-05 20:37:42
【问题描述】:
我已将“选择”的默认值设置为下拉菜单的“0”。
验证规则
1.根据需要选择下拉菜单。(至少从下拉菜单中选择一个选项)。
2.如果没有选择某个值,则显示错误提示“您需要选择一个选项”
我尝试过的事情:
案例一:
HTML:
<div class="col-12 col-md-6 col-lg-4">
<div class="form-group">
<span class="plain-select">
<select class="form-control" id="select101" formControlName="UserId"
[(ngModel)]="editFormData.userId">
*****<option value='0' selected>Select</option>*****
<option *ngFor="let user of usernames" value={{user.userId}}>
{{user.usernames}}
</option>
</select>
</span>
<div
*ngIf="addUserForm.controls['UserId'].invalid && (submited || ` addUserForm.controls['UserId'].dirty || addUserForm.controls['UserId'].touched)"`
class="error-msg">
<div *ngIf="addUserForm.controls['UserId'].errors.required">
UserId is required.
</div>
</div>
</div>
</div>
TypeScript:
UserId: ['', [Validators.required, Validators.min(1)]],
**以上情况:
I am able to see the default as "Select" but the validation doesn't work.
当没有从下拉列表中选择任何选项时,它不会给出任何验证错误。
案例 2:
<div class="col-12 col-md-6 col-lg-4">
<div class="form-group">
<span class="plain-select">
<select class="form-control" id="select101" formControlName="UserId"
[(ngModel)]="editFormData.UserId">
<option value='null' selected>Select</option>
<option *ngFor="let user of usernames" value={{user.userId}}>
{{user.usernames}}
</option>
</select>
</span>
<div
*ngIf="addUserForm.controls['UserId'].invalid && (submited || addUserForm.controls['UserId'].dirty || addUserForm.controls['UserId'].touched)"
class="error-msg">
<div *ngIf="addUserForm.controls['UserId'].errors.required">
UserId is required.
</div>
</div>
</div>
</div>
TypeScript:
UserId: ['', [Validators.required, Validators.min(1)]],
In the above case, the validation is working as expected but however the default value is not set to "Select" and also the validation works only if "Select" option is selected from the dropdown
Case-3:
Same happens when i select the value to "undefined".
【问题讨论】:
标签: html angular validation dropdown angular-ng-if