[FIXED] Select/Unselect and get values of dynamically generated checkbox using ngModel directive in Angular

Issue

I have a set of data response from an API and dynamically generating checkboxes on my HTML file using DataView component of PrimeNG.

The goal is to have a functionality where I can select/unselect all checkbox via button click and store their values in an array, for example.

Here’s what I have so far;

Component HTML

<p-dataView [value]="requestList" {...} >
  <ng-template let-request pTemplate="listItem">
    <p-checkbox
      name="reqNo"
      inputId="reqNo"
      (click)="getCheckBoxValue()"
      value="{{ request.requestNo }}"
      [(ngModel)]="reqNo"
      [ngModelOptions]="{ standalone: true }"
    ></p-checkbox>
  </ng-template>
</p-dataview>

Main TS File

reqNo: any; reqNo is binded using ngModel.

Giving me arrays of values when consoled;
['R08000036', 'R08000002']

Each object in the API response looks like this;

{
  requestNo: "R08000036",
  requestBy: "SUPER_USER",
  requestTs: "2021-02-18T04:27:05.710+0000",
  collectTs: "2008-07-30T16:00:00.000+0000",
  testReason: "After Visit",
  noOfPrisoner: 2,
  status: "Printed",
  printTs: "2008-07-21T16:00:00.000+0000",
  escortingOfficer: "00552",
}

getCheckBoxValue event handler;

getCheckBoxValue() {
  console.log(this.reqNo);
}

I’m new to Angular and I think I’m using the ngModel wrong. Can someone please teach me?

Solution

You can select all values by setting a new value for reqNo by values from requestList.

selectAll() {
  this.reqNo = this.requestList.map(item => item.requestNo);
}
unselectAll() {
  this.reqNo = [];
}

Example

Answered By – Yan Koshelev

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published