2017-10-04 87 views
0

我有一个html码,其中我迭代数组:定制验证器来在ngFor回路中产生复选框

<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.如何添加到每个复选框的值为ngModel这将来自后端标题为g.confirm

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

回答

0

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

NgModel将更改数据从中拉出的数组,然后当您单击save调用save()函数时,可以检查创建复选框的数组,以查看是否所有的确认属性都为true,并且然后提交它或显示错误。

0

您可以在窗体更改上设置侦听器并保留辅助数组以遵循该过程。只要所有人都打勾,将该按钮设置为禁用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" ...>.....