Search code examples
angularcheckboxangular-ngmodelprimeng-datatablengmodel

ngModel doesn't work using primeng table with native checkbox


I'm using primeng editable table with native checkbox and ngModel.

<p-table id="resultTable" [columns]="cols" [value]="results" [rowTrackBy]="trackByFunction" 
scrollable="true" selectionMode="single" [selection]="selected" (onRowSelect)="onRowSelect($event.data)">
  ...
  <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">
    <tr [pSelectableRow]="rowData">
      ...
      <td>
        <div class="text-center">
          <input type="checkbox" [(ngModel)]="rowData.active">
        </div>
      </td>
      ...
    </tr>
  </ng-template>
  ...
</p-table>

somehow, the [(ngModel)] doesn't work, I can only get the value of rowData.active, but when I click the checkbox, the event binding is not working, the value didn't change after clicked.

Dose anyone know why?


Solution

  • [(ngModel)] is not very stable in multiple situations. Sometimes it works immediately,sometimes it should take some time. The right way to do this is using [(ngModel)] with (ngModelChange)

    <input type="checkbox" [(ngModel)]="rowData.active" (ngModelChange)="fun(rowData)">
    

    should notice that:

    if (ngModelChange) is in front of [(ngModel)], it will get the value before change, otherwise it will get the changed value