代码之家  ›  专栏  ›  技术社区  ›  Idris.AH

包含复选框的角度2/5条件验证

  •  0
  • Idris.AH  · 技术社区  · 8 年前

    我有一个反应式表单,它有一个带有复选框的表,每行有一些用户输入。如果用户选中复选框,则需要填写相应的输入。e、 g.如果勾选了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>
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Udi Mazor    8 年前

    方法是使用跨域自定义验证器。 您需要将两个表单控件嵌套在一个表单组中(在ts和html中)。然后,您需要构建一个自定义验证器并将其附加到此表单组。

    推荐文章