下拉列表验证角度

时间:2020-04-01 09:03:54

标签: html angular

要打印*如果未选择“下拉列表”值,则必须提交。

这是我的html。

 <select [(ngModel)]="selectedCategory.id" formControlName="Category" (change)="onSelect($event.target.value)" [ngClass]="{ 'is-invalid': submitted && Category.errors }">
            <option value="0">--Select--</option>
            <option *ngFor="let category of categories" [ngValue]="category">{{category.name}}</option>
          </select>
          <div *ngIf="submitted && Category.errors" class="invalid-feedback">
            <div *ngIf="Category.errors.required">Category is required</div>
        </div>
<button class="btn btn-primary"   >Add to Cart</button>

这是我的ts文件。

cart_form = new FormGroup({
    Category: new FormControl('', Validators.required),

  });

1 个答案:

答案 0 :(得分:0)

您需要将html更改为:

 <form [formGroup]="cart_form" >

    <select formControlName="category" (change)="onSelect($event.target.value)">
            <option [ngValue]="null">--Select--</option>
            <option *ngFor="let item of categories">{{item.name}}</option>
          </select> 
          <div *ngIf="!cart_form.controls.category.valid" class="invalid-feedback">
            <div *ngIf="cart_form.controls.category.errors.required">Title is required</div>
        </div>

        <button type="submit" [disabled]="cart_form.invalid">Submit</button>
</form>

和您的组件

categories = [ {id: 1, name : 'test1'}, {id: 2, name : 'test12'}];
      selectedCategory = null;

      cart_form = new FormGroup({
        category: new FormControl(null, Validators.required),

      });

我为您制作了一个演示 https://stackblitz.com/edit/input-ngmodel-pnm31t?file=app/app.module.ts