通过 primeng `
在 Angular 中结合 PrimeNG 使用表格(
在模板中,为
{{ item.name }} {{ item.id }}
? 注意:selectionMode="multiple" 是启用多选的必要配置;若仅需单选,可设为 "single",此时 selectedItems 类型应为 any | null。
export class MyComponent {
items: any[] = [
{ id: 1, name: '项目A' },
{ id: 2, name: '项目B' },
{ id: 3, name: '项目C' }
];
selectedItems: any[] = []; // 多选模式下必须初始化为空数组
handleSelectedItems(items: any[]): void {
if (items.length === 0) {
console.warn('未选中任何项');
return;
}
console.log('已选中:', items);
// ✅ 此处可安全调用服务、弹窗、导出等业务逻辑
}
}
见错误与修正❌ 错误:在
✅ 修正:统一使用 let-item 声明的上下文变量 —— [pSelectableRow]="item"
❌ 错误:未初始化 selectedItems 或类型不匹配(如声明为 undefined 或 null)
✅ 修正:严格按选择模式初始化 —— 多选用 any[] = [],单选用 any | null = null
❌ 错误:试图在 (onClick) 中动态传入 selectedItemsIWantToPass(模板中无此变量)
✅ 修正:放弃“传参思维”,改用组件属性直取 —— selectedItems 已由 PrimeNG 自动更新
通过这一模式,代码更简洁、可维护性更高,也完全符合 Angular 的响应式设计理念。