猿问

下拉列表验证角度

如果未选择下拉值,则需要打印 *提交时需要。


这是我的 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),


  });


墨色风雨
浏览 79回答 1
1回答

千巷猫影

您需要将 html 更改为:&nbsp;<form [formGroup]="cart_form" >&nbsp; &nbsp; <select formControlName="category" (change)="onSelect($event.target.value)">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option [ngValue]="null">--Select--</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option *ngFor="let item of categories">{{item.name}}</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </select>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div *ngIf="!cart_form.controls.category.valid" class="invalid-feedback">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div *ngIf="cart_form.controls.category.errors.required">Title is required</div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" [disabled]="cart_form.invalid">Submit</button></form>你的组件categories = [ {id: 1, name : 'test1'}, {id: 2, name : 'test12'}];&nbsp; &nbsp; &nbsp; selectedCategory = null;&nbsp; &nbsp; &nbsp; cart_form = new FormGroup({&nbsp; &nbsp; &nbsp; &nbsp; category: new FormControl(null, Validators.required),&nbsp; &nbsp; &nbsp; });我为你构建了一个演示&nbsp;https://stackblitz.com/edit/input-ngmodel-pnm31t?file=app/app.module.ts
随时随地看视频慕课网APP

相关分类

Html5
我要回答