2017-10-04 50 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" ...>.....