Home > database >  Primeng, dynamically uncheck p-checkbox with pButton
Primeng, dynamically uncheck p-checkbox with pButton

Time:10-07

i originally found this question, which is really similar to my situation:

how to uncheck/check a primeng checkbox manually

and this is a StackBlitz where it shows my problem:

https://stackblitz.com/edit/angular-primeng-p-checkbox-issue-6xjv8b?file=app/app.component.ts

basically, i am looping through data that can be any length and displaying it in a table.

one of the columns just has a p-checkbox with (onChange), that when checked and unchecked, it passes in some parameters for me to keep track of in an array.

i am trying to then uncheck all the p-checkboxes with a button click.

i found another question/solution that mentioned using @ViewChildren, ElementRef, QueryList but it was having a problem trying to figure out what "nativeElement.checked" was.

and other questions/solutions i found involved knowing the length of the checkboxes beforehand, and using *ngFor through an array to display the correct amount of checkboxes. i tried to use similar logic with my setup, but couldn't get it working either.

CodePudding user response:

Why not using [(ngModel)]="arrayOfChecked" in the template?

And in the button (click) event handler the array reference needs to be changed to a new empty array, since component change detection won't be fired if object reference is the same (i. e. after pop() or push()).

Here is a solution based on your StackBlitz example.

https://stackblitz.com/edit/angular-primeng-p-checkbox-issue-6euntp?file=app/app.component.ts

CodePudding user response:

Simply you can control the checkboxes within your model

  tableData: { id: number; name: string; isChecked?: boolean }[] = [
    { id: 1, name: 'first' },
    { id: 2, name: 'second' },
    { id: 3, name: 'third' },
  ];

Then add ngModel to the html

<tr>
  <td>{{ tdata.id }}</td>
  <td>{{ tdata.name }}</td>
  <td colspan="2">
    <p-checkbox
      #checkboxes
      [(ngModel)]="tdata.isChecked"
      binary="true"
      inputId="binary"
      (onChange)="changeCheckmark($event, tdata.id, tdata.name)"
    ></p-checkbox>
  </td>
</tr>

and reset the state

  clickButton() {
    this.tableData.filter(z => z).forEach((x) => (x.isChecked = false));
  }
  • Related