简体   繁体   中英

Handle selection p-checkbox with the same group

I have a list like below:

 rows: any[] = [{"id":"1721079361", "type":"0002", "number":"2100074912"},
                {"id":"1721079363", "type":"0003", "number":"2100074913"},
                {"id":"1721079363", "type":"0004", "number":"2100074914"},
                {"id":"1721079361", "type":"0001", "number":"2100074911"}];

I want to load on the table with the checkbox. 在此处输入图像描述

The user only selects the items which have the same Id. Here is HTML

<p-table [value]="rows">
    <ng-template pTemplate="header">
        <tr>
           <td>
                </td>
            <th>ID</th>
            <th>Type</th>
            <th>Number</th>
        </tr>
    </ng-template>
      <ng-template   pTemplate="body" let-row>
         <tr [pSelectableRow]="row">
           <td>
                <p-checkbox [(ngModel)]="selectedValues" value="{{row.id}}"></p-checkbox>
            </td>
            <td>{{row.id}}</td>
            <td>{{row.type}}</td>
            <td>{{row.number}}</td>
        </tr>
    </ng-template>
</p-table>

Test : {{selectedValues}}

But until now, I cannot find the solution for it. Pls advice https://stackblitz.com/edit/angular-8ddptg

You can use disable property and bind it with row value, dynamically on change event of any checkbox.

component.html

<p-checkbox [disabled]="row && row.isDisable" [(ngModel)]="selectedValues" value={{row.id}}" (onChange)="updateList(selectedValues)" ></p-checkbox>

component.ts

updateList(val){
    if(val.length === 0){
      for(let i = 0; i<this.rows.length ;i++){
        this.rows[i]['isDisable'] = false;
      }
    }else{
       let id = val[0];
        for(let i = 0; i<this.rows.length ;i++){
          if(this.rows[i]['id']!== id){
            this.rows[i]['isDisable'] = true;
          }
        }
    }

  }

Here is working code

Hope this solve your purpose!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM