Search code examples
javascriptangularcheckboxprimengangular-ngmodel

ngModel updated but the change not showing in the view in PrimeNG checkbox


I have a list of PrimeNG checkboxes. I have an array binded to it with ngModel called selectedItems. I also have initially checked items in that array. I have a situation where I add items to the selectedItems not by checking the checkbox but by doing some other action (calling a function). For example by clicking a button situated somewhere else. My issue is I can see that when I console log the item is added to the selectedItems array but the view has not been updated.

this is the code i used to test

    selectedItems: any[] = [{ name: 'Accounting', key: 'A' }];

    items: any[] = [
        { name: 'Accounting', key: 'A' },
        { name: 'Marketing', key: 'M' },
        { name: 'Production', key: 'P' },
        { name: 'Research', key: 'R' }
    ];

    selectSomething(){
        this.selectedItems.push({ name: 'Production', key: 'P' })
    }

and the template

<div class="card flex justify-content-center">
    <div class="flex flex-column gap-2">
        <div *ngFor="let item of items" class="field-checkbox">
            <p-checkbox name="group" [value]="item" [(ngModel)]="selectedItems" [inputId]="item.key" ></p-checkbox>
            <label [for]="item.key">{{ item.name }}</label>
        </div>
    </div>
    
</div>
<button (click)="selectSomething()">Select Something</button>

Solution

  • When you push element to the array, change detection of p-checkbox is not fired because reference to the array is the same and p-checkbox uses OnPush strategy

    So you need to make a new array:

    selectSomething() {
      this.selectedItems = [...this.selectedItems, { name: 'Production', key: 'P' }] 
    }