簡體   English   中英

根據復選框值動態更改文本

[英]change text dynamically based on checkbox value

使用FormArray我在我的組件上綁定了復選框,復選框的默認labelselect ,當我單擊復選框時, label selectAll改為選中的每個復選框的所有復選框(所有復選框的更改true )並將文本更改為selected ,我的問題是:

  • 當我 select 只有一個復選框時,更改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>

https://stackblitz.com/edit/angular-43suh3?file=src/app/inquiry-response/inquiry-response.component.html

我做了一些改變,你可以試試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM