[英]change text dynamically based on checkbox value
使用FormArray
我在我的組件上綁定了復選框,復選框的默認label
是select ,當我單擊復選框時, label
selectAll
改為選中的每個復選框的所有復選框(所有復選框的更改true
)並將文本更改為selected ,我的問題是:
label
也會影響其他復選框selectAll
復選框時,所有復選框 label 將更改為選中,然后如果我取消選中單個復選框,它應該將label
更改為select這是我嘗試過的:
html文件
<div *ngIf="isShowResponse">
<p>Inquiry Response</p>
<form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
<ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
<ng-container [formGroupName]="i">
<input type="checkbox" formControlName="isChecked"
(change)="checkedState(summon)">
{{ summonText }}
</ng-container>
</ng-container>
</form>
<!-- <pre>{{form.value | json}}</pre> -->
<button (click)="selectAll()">Select All</button>
</div>
ts文件
checkedState(summon) {
summon.checked = !summon.checked;
this.summonText = summon.checked === true ? 'selected' : 'select';
}
selectAll() {
this.formReceivedSummons.controls.map(value => value.get('isChecked').setValue(true));
return this.summonText = 'selected';
}
這是我完整的 stackblitz 演示,我可以使用一些建議和更好的實踐來解決這個問題
<div *ngIf="isShowResponse">
<p>Inquiry Response</p>
<form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
<ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
<ng-container [formGroupName]="i">
<input type="checkbox" formControlName="isChecked">
{{ summon.get('isChecked').value ? 'selected' : 'select' }}
</ng-container>
</ng-container>
</form>
<!-- <pre>{{form.value | json}}</pre> -->
<button (click)="selectAll()">Select All</button>
</div>
我做了一些改變,你可以試試這個:
HTML
<div *ngIf="isShowResponse">
<p>Inquiry Response</p>
<form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
<ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
<ng-container [formGroupName]="i">
<input type="checkbox" [checked]="summon.checked" formControlName="isChecked"
(change)="checkedState(summon)">
{{ summon.checked === true ? 'selected' : 'select' }}
</ng-container>
</ng-container>
</form>
<!-- <pre>{{form.value | json}}</pre> -->
<button (click)="selectAll()">Select All</button>
</div>
在函數中:
selectAll() {
this.formReceivedSummons.controls.map((summon: any) => {
summon.checked = true;
});
}
checkedState(summon) {
summon.checked = !summon.checked;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.