简体   繁体   English

Angular 5 ngForm:无法验证表单提交时的选择框选项

[英]Angular 5 ngForm: unable to validate select box option on form submission

I want to validate the select box on ngForm submission.我想验证ngForm提交时的选择框。
The code is below:代码如下:

<select name="maincatList"
        id="maincatList"
        [ngModel]="cat"
        #cat_list="ngModel"
        class="form-control"
        required>
          <option value="">Select</option>
          <option *ngFor="let cat of responseRawCatList" [value]="cat.id">{{cat.categoryName}}</option>
</select>
<div *ngIf="contentStandalonrFrm.submitted && cat.invalid" class="invalid-feedback">
  <div *ngIf="cat.errors.required">Field is required</div>
</div>

I want that user cannot be able to submit the form without selecting a value in the select box.我希望用户无法在不选择选择框中的值的情况下提交表单。 It should show the validation error.它应该显示验证错误。

Case 1: When I submit the button with the value = "" , the form is not showing any error and no submission happen.案例 1:当我提交带有value = ""的按钮时,表单没有显示任何错误并且没有提交发生。

Case 2: If I select any value and press submit, the form is submitted.情况 2:如果我选择任何值并按提交,则提交表单。

You need to refer the #cat_list="ngModel" for validation and hence it should be cat_list and not cat ..您需要参考#cat_list="ngModel"进行验证,因此它应该是cat_list不是cat ..

Change:改变:

<div *ngIf="contentStandalonrFrm.submitted && cat.invalid" class="invalid-feedback">
  <div *ngIf="cat.errors.required">Field is required</div>
</div>

To:到:

<div *ngIf="contentStandalonrFrm.submitted && cat_list.invalid">
    <div *ngIf="cat_list.errors.required" class="text-danger">Field is required</div>
</div>

Also try removing the class class="invalid-feedback" which also prevents the error message from displaying.. Because it has the css property as display:none ..还尝试删除类class="invalid-feedback"这也阻止显示错误消息.. 因为它的 css 属性为display:none ..

Working Stackblitz 工作堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM