我正在使用 PrimeNG 表,并且我想以编程方式处理保存行编辑,以防在编辑模式下存在任何需要事先解决的自定义验证错误。目前,我已将 pSaveEditableRow 添加到一个按钮,单击该按钮即可结束行编辑并保存对该行所做的编辑。我需要覆盖它并预先进行一些验证。如何才能做到这一点?
我查看了 PrimeNG 的文档,看起来我可以调用“saveRowEdit”函数,但我需要传递 rowData 和 rowElement,它们都来自 pEditableRow,并且 pEditableRow 似乎设置为具有表所需属性的对象。
对于那些想要手动结束一行编辑模式的人,我找到了一个解决方案:
从
pSaveEditableRow
标签中删除 button
(如果您已添加)。 正如文档所述,pSaveEditableRow
只需将行切换回查看模式即可。
将
#htmlTableRowElement
添加到您的 <tr>
标签:<tr [pEditableRow]="rowData" #htmlTableRowElement>...</tr>
将
rowData
和 htmlTableRowElement
传递到 (click)
标签上的 button
函数。
将
import { Table } from 'primeng/table'
添加到您的组件中。
将
@ViewChild('dt', { static: false }) table: Table
添加到您的组件中。
将
#dt
添加到您的 <p-table>
:<p-table #dt>...</p-table>
您现在可以在单击按钮时调用的函数中调用
this.table.saveRowEdit(rowData, htmlTableRowElement)
。这将结束该行的编辑模式并将其置于查看模式。 rowData
是 any 的类型(包含行数据的对象),并且 htmlTableRowElement
非常不言自明。
希望这有帮助!
从这里,在第二个示例中,您注意到有 3 个按钮,每个按钮绑定到不同的功能:
<button *ngIf="!editing" pButton pRipple type="button" pInitEditableRow icon="pi pi-pencil" (click)="onRowEditInit(product)" class="p-button-rounded p-button-text"></button>
<button *ngIf="editing" pButton pRipple type="button" pSaveEditableRow icon="pi pi-check" (click)="onRowEditSave(product)" class="p-button-rounded p-button-text p-button-success mr-2"></button>
<button *ngIf="editing" pButton pRipple type="button" pCancelEditableRow icon="pi pi-times" (click)="onRowEditCancel(product, ri)" class="p-button-rounded p-button-text p-button-danger"></button>
在我看来,在这三个选项之间,你应该能够完成你需要做的任何事情。根据您的要求,当用户单击复选标记按钮进行保存时,您将执行验证逻辑并继续保存,或通知用户该行中的一对多字段不正确。