以下是在单击 PrimeNG 表中的另一行时实现退出行编辑所需行为的代码:
<p-table [value]="products" dataKey="id">
<ng-template pTemplate="header">
<tr>
<th></th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-product let-rowIndex="rowIndex" let-editing="editing">
<tr [pEditableRow]="product" [pEditing]="editing">
<td>
<button *ngIf="!editing" pButton type="button" icon="pi pi-pencil"
(click)="onRowEditInit(product, rowIndex)" class="p-button-rounded p-button-text"></button>
<button *ngIf="editing" pButton type="button" icon="pi pi-check"
(click)="onRowEditSave(product, rowIndex)" class="p-button-rounded p-button-text p-button-success mr-2"></button>
<button *ngIf="editing" pButton type="button" icon="pi pi-times"
(click)="onRowEditCancel(product, rowIndex)" class="p-button-rounded p-button-text p-button-danger"></button>
</td>
<td>
<div *ngIf="!editing; else editMode">
{{ product.name }}
</div>
<ng-template #editMode>
<input type="text" [(ngModel)]="product.name">
</ng-template>
</td>
<td>
<div *ngIf="!editing; else editMode">
{{ product.price }}
</div>
<ng-template #editMode>
<input type="text" [(ngModel)]="product.price">
</ng-template>
</td>
<td>
<button *ngIf="editing && rowIndex !== editingRowIndex" pButton type="button" icon="pi pi-check"
(click)="onRowEditSave(products[editingRowIndex], editingRowIndex)"
class="p-button-rounded p-button-text p-button-success"></button>
<button *ngIf="editing && rowIndex !== editingRowIndex" pButton type="button" icon="pi pi-times"
(click)="onRowEditCancel(products[editingRowIndex], editingRowIndex)"
class="p-button-rounded p-button-text p-button-danger"></button>
</td>
</tr>
</ng-template>
</p-table>
在此代码中,我对您现有的代码进行了一些修改。关键的变化是我在每行的“保存”和“取消”按钮中添加了一个条件
rowIndex !== editingRowIndex
。此条件可确保仅当当前正在编辑的行与您单击的行不同时才显示保存或取消编辑的按钮。这样,点击另一行就会退出上一行的编辑模式。 editingRowIndex
变量用于跟踪当前正在编辑的行。