【问题标题】:Custom validator to generated checkboxes in ngFor loop在 ngFor 循环中生成复选框的自定义验证器
【发布时间】:2017-10-04 17:20:07
【问题描述】:

我有一个 html 代码,我在其中迭代一个数组:

<div class="container">
  <ol *ngFor="let g of guides">
    <button  type="button" class="form-control" (click)="open(g)" [class.not-confirmed]="!g.confirm" [class.confirmed]="g.confirm">{{g.description}}</button>
    <div [hidden]="!g.canOpen" style="text-align: center">
      <p>test</p>
      <label>Zapoznałem się</label>
      <input type="checkbox" [(ngModel)]="g.confirm">
    </div>
  </ol>
  <button class="btn btn-default form-control" (click)="save()">Save</button>
</div>

是否可以编写一个自定义验证器来检查是否所有复选框都被勾选(选中),然后使最后一个按钮“保存”可供点击?我开始编写一些代码为reactive forms,但这对我来说很难: 1.如何处理根据数组大小生成的多个复选框? 2.如何将来自后端g.confirmngModel添加到每个复选框值?

  form = new FormGroup({
    confirmation: new FormControl()
  }, CustomValidator.checkAllCheckboxes); 

【问题讨论】:

    标签: javascript forms angular angular-forms


    【解决方案1】:

    如果 g.confirm 是布尔值,应该可以正常工作。

    NgModel 会改变拉取数据的数组,然后当你点击 save 调用 save() 函数时,你可以检查创建复选框的数组,看看是否所有的确认属性都为真,然后要么提交,要么显示错误。

    【讨论】:

      【解决方案2】:

      您可以在表单更改时设置一个侦听器并保留一个辅助数组来跟踪该过程。勾选所有选项后,将按钮禁用设置为 false。类似于以下内容:

      打字稿

      ...
      enabledButton: boolean;
      auxiliary=[] //same size as the checkboxes number
      @ViewChild('myForm') myForm: NgForm;
      myForm: NgForm;
      ....
      ngOnInit() {
          this.myForm.valueChanges.subscribe((value: any) => {
               console.log("One of the checkbox was touched");
               // here check if the all values of the auxiliary array are true
               //if so:
               this.enableButton = true
          });
      }
      

      HTML

      <button type="submit" [disabled]="enabledButton" ...>.....
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-08
        • 2011-07-24
        • 1970-01-01
        • 2012-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多