Angular PrimeNG Table 组件:单选模式下如何锁定选中行
在 Angular PrimeNG Table 组件中,设置了 selection 属性和 <p-tableRadioButton> 后,可以实现单选模式。但默认情况下,用户可以取消选中当前行。本文介绍如何通过监听 <p-tableRadioButton> 组件的 change 事件,并控制其他行的选中状态来实现锁定选中行功能,防止用户取消选择。
步骤:
-
监听 change 事件:
在模板中,将
<p-tableRadioButton>组件的 change 事件绑定到onRowSelect方法:<p-table [value]="data" selectionMode="single"> <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex"> <tr [pSelectableRow]="rowData"> <td><p-tableRadioButton [value]="rowData" (change)="onRowSelect(rowData)"></p-tableRadioButton></td> <td>{{rowData.col1}}</td> <td>{{rowData.col2}}</td> </tr> </ng-template> </p-table> -
实现 onRowSelect 方法:
在组件中,实现
onRowSelect方法,用于处理 change 事件。selectedRow: any; onRowSelect(rowData: any) { if (this.selectedRow === rowData) { return; } this.selectedRow = rowData; this.data.forEach((item) => { if (item !== rowData) { item.selected = false; // 设置其他行 RadioButton 为不可选中状态 } }); }在这个方法中,我们使用
selectedRow变量记录当前选中的行。当用户选择不同的行时,我们会将新选中的行设置为选中状态,并遍历所有其他行,将它们的selected属性设置为false,从而将它们的 RadioButton 设置为不可选中状态。
示例代码:
<p-table [value]="data" selectionMode="single">
<ng-template pTemplate="header">
<tr>
<th style="width: 2.5em"></th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">
<tr [pSelectableRow]="rowData">
<td><p-tableRadioButton [value]="rowData" (change)="onRowSelect(rowData)"></p-tableRadioButton></td>
<td>{{rowData.col1}}</td>
<td>{{rowData.col2}}</td>
</tr>
</ng-template>
</p-table>
selectedRow: any;
onRowSelect(rowData: any) {
if (this.selectedRow === rowData) {
return;
}
this.selectedRow = rowData;
this.data.forEach((item) => {
if (item !== rowData) {
item.selected = false; // 设置其他行 RadioButton 为不可选中状态
}
});
}
通过以上步骤,您可以在 PrimeNG Table 组件中实现锁定选中行的功能,用户只能选择不同的行,而无法取消选择当前行。
原文地址: https://www.cveoy.top/t/topic/mU4F 著作权归作者所有。请勿转载和采集!