【问题标题】:Angular 2/5 conditional validation involving checkbox涉及复选框的 Angular 2/5 条件验证
【发布时间】:2018-09-15 20:51:59
【问题描述】:

我有一个反应式表单,它有一个带有复选框的表格,每行都有一些用户输入。我想这样做,如果用户选中一个复选框,则需要填写相应的输入。例如如果选中了 11+,但未填写相应的用户输入(即价格)并且用户尝试按下添加按钮,则它不应该提交表单,它应该提供一条消息。我不确定如何有条件地应用此逻辑。

TS 中的表格:

this.addSubjectForm = new FormGroup({
  'type' : new FormControl(null, Validators.required),
  'subject' : new FormControl(null, Validators.required),
  'discount' : new FormControl(null),
  'levelDefinition' : new FormGroup({
    '11+' : new FormControl(null),
    'KS3' : new FormControl(null),
    'GCSE' : new FormControl(null),
    'A-Level' : new FormControl(null),
    'Degree' : new FormControl(null)
  })

HTML 表格/表单:

<form [formGroup]="addSubjectForm" (ngSubmit)="onAddSubject()">
      <!-- the first three inputs (type, subject and discount) are not included here to reduce the amount of code shown in the question -->
      <div formGroupName="levelDefinition">
        <table class="table table-bordered table-condensed table-hover">
            <thead>
                <tr>
                  <th class="text-center">
                        <input type="checkbox" name="all" 
                        (change)="isSelected = !isSelected" />
                    </th>
                    <th>Level</th>
                    <th>Price</th>
                    <th>Discounts</th> 
                </tr>
            </thead>
            <tbody>
              <tr *ngFor="let level of levels ; let i = index">
                <td class="text-center" >
                    <input type="checkbox" 
                    value="{{level.id}}" 
                    appHighlightOnCheck
                    formControlName="{{level}}"
                    [checked]="isSelected" />
                </td>
                <td class="text-center">{{ level }}</td>
                <td>
                  <input
                  type="text"
                  class="form-control">
                </td>
                <td>
                  <input
                  type="text"
                  class="form-control">
                </td>
              </tr>
            </tbody>
          </table>
        </div>  
    </form>
    <button class="btn btn-primary" type="submit">Add</button>

【问题讨论】:

标签: angular angular5 angular2-forms angular-reactive-forms angular-validation


【解决方案1】:

这样做的方法是使用跨字段自定义验证器。 您需要将 2 个表单控件与一个表单组嵌套(在 ts 和 html 中)。然后您需要构建一个自定义验证器并将其附加到这个 formGroup。

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多