I have a PrimeNG v12.2 p-table
component abbreviated as follows:
<p-table
[(selection)]="selectedMessages"
selectionMode="multiple">
I need to programmatically select the row the user just clicked on. I figured I would just push a new object to selectedMessages
in the click, but it does not work. The object is pushed, but nothing remains selected.
I need to handle the right-click. The row is defined as:
<tr (contextmenu)="clickMessage(message)">
The event is handled with:
clickMessage(mail: MailboxItem): void {
this.selectedMessages.push(mail);
}
The member is initialized to empty:
selectedMessages: MailboxItem[] = [];
My event fires properly, the object goes from empty ([]
) to having one MailboxItem
in it, but no table rows are selected.
The issue here is that Angular change detection only occurs when the array bound to [(selection)]
is modified.
The solution is to re-assign to the array itself which will trigger change detection and properly select the row:
this.selectedMessages = [...this.selectedMessages, mail];
In my use-case we want to de-select all rows except the one being right-clicked on, so it is simply:
this.selectedMessages = [ mail ];