首页 > 解决方案 > 如何使表单中的所有字段都需要

问题描述

我正在处理我的 Angular2 项目。我已经开发了一个表格,我想填写所有必需的字段。我试图使 Title 成为必需,但它没有显示所需的输出。我不明白出了什么问题。请指导我正确的方向。

# product-form.component.html
<form #f="ngForm" (ngSubmit)="save(f.value)">
  <div class="form-group">
    <label for="title">Title</label>
    <input #title="ngModel" ngModel name="title" id="title" type="text" class="form-control">
    <div class="alert alert-danger" *ngIf="title.touched && title.invalid">
         Title is required. 
    </div>
  </div>
  <div class="form-group mb-3">
    <label for="price">Price</label>
    <div class="input-group-prepend">
      <span class="input-group-text">$</span>
      <input ngModel name="price" id="price" type="number" class="form-control">
    </div>
  </div>
  <div class="form-group">
    <label for="category">Category</label>
    <select ngModel name="category" id="category" class="form-control">
      <option value=""></option>
      <option *ngFor="let c of categories$ | async" [value]="c.$key">
        {{ c.name }}
      </option>  
    </select>
  </div>
  <div class="form-group">
    <label for="imageUrl">image URL</label>
    <input ngModel name="imageUrl" id="imageUrl" type="imageUrl" type="text" class="form-control">
  </div>  
  <button class="btn btn-primary">Save</button>
</form>

标签: angular

解决方案


正如我在评论中回答的那样,OP 必须使用 HTML5 [required] 属性来输入标签,以便根据需要进行设置。


推荐阅读