【问题标题】:Programmatic row selection in a p-table using selectionMode 'multiple'使用 selectionMode 'multiple' 在 p 表中进行编程行选择
【发布时间】:2021-11-14 23:31:18
【问题描述】:

我有一个 PrimeNG v12.2 p-table 组件缩写如下:

<p-table
   [(selection)]="selectedMessages"
   selectionMode="multiple">

我需要以编程方式选择用户刚刚单击的行。我想我会在点击中将一个新对象推送到selectedMessages,但它不起作用。对象被推送,但没有任何内容保持选中状态。

我需要处理右键单击。该行定义为:

<tr (contextmenu)="clickMessage(message)">

事件的处理方式:

clickMessage(mail: MailboxItem): void {
    this.selectedMessages.push(mail);
}

成员初始化为空:

selectedMessages: MailboxItem[] = [];

我的事件正确触发,对象从空 ([]) 变为其中有一个 MailboxItem,但没有选择表行。

【问题讨论】:

  • 我不理解为“需要调试详细信息”而关闭的投票。我还能提供什么?

标签: angular primeng primeng-turbotable


【解决方案1】:

很抱歉,我现在无法对此进行测试,但我想您应该将 MailboxItem 对象的 id 作为 "dataKey" 放入表中。

例如,如果您的邮件行从这样的数组中获取值:

mailsArray: MailboxItem[]  =
[ 
 { 
   myId=1; 
   from="Patrick"; 
   message="Blah,blah,bla..";
 },
 { 
   myId=2; 
   from="Swaiczwe"; 
   message="Lorem blahblah etceterabla..";
 }
];

那么你的表应该有这样的 dataKey 属性:

<p-table
   [(selection)]="selectedMessages"
   selectionMode="multiple"
   [value]="mailsArray"
   dataKey="myId"
>

最后,你的方法 clickMessage() 应该是这样的:

clickMessage(mail: MailboxItem): void {
    this.selectedMessages.push(mail.myID);
}

你也应该在你的 header 和 body 模板中加入类似的东西(抱歉,你没有展示你是如何拥有它的,所以它是近似的):

<ng-template pTemplate="header">
   <tr [pSelectableRow]="mail">
                <th>Id</th>
                <th>From</th>
                <th>Message</th>
   </tr>
</ng-template>

<ng-template pTemplate="body" let-mail  let-rowIndex="rowIndex">
            <tr [pSelectableRow]="mail" [pSelectableRowIndex]="rowIndex">
                <td>{{mail.myId}}</td>
                <td>{{mail.from}}</td>
                <td>{{mail.message}}</td>
            </tr>
</ng-template>

P.S: 也试试改

<ng-template pTemplate="header">
   <tr [pSelectableRow]="mail">

只是为了一个“简单”,像这样:

<ng-template pTemplate="header">
   <tr>

【讨论】:

  • 感谢您的尝试,但使用dataKey 不起作用。我也不能在标题模板中做&lt;tr [pSelectableRow]="mail"&gt;,因为mail 是正文中的let-mail,它在标题中不可用。
  • 对不起,我的答案的最后一部分没有显示。我现在已经编辑了。
【解决方案2】:

这里的问题是只有在绑定到[(selection)] 的数组被修改时才会发生角度变化检测。

解决方案是重新分配给数组本身,这将触发更改检测并正确选择行:

this.selectedMessages = [...this.selectedMessages, mail];

在我的用例中,我们想要取消选择除右键单击之外的所有行,因此很简单:

this.selectedMessages = [ mail ];

【讨论】:

  • this.selectedMessages = [...this.selectedMessages, mail]; 会是更好的合成器。
猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 2010-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多