我使用的是primeng表。每个表都有自己的列。 表格示例:
annexOneTable: any[] = [
{ name: 'N0.', field: 'declarationOrder', width: '2rem' },
//other fields
];
isDateField(value: any, fieldName: string): boolean {
//return true when date otherwise false
}
isNumberField(value: any, fieldName: string): boolean {
//return true when numberotherwise false
}
trackRecord(index: number, record: any) {
return record.id;
}
formatValue(value: any, fieldName: string): string {
//return the wanted format as string for specific fields
}
<p-table
[value]="declarationList"
styleClass="p-datatable-gridlines"
[tableStyle]="{ 'min-width': '50rem' }"
[columns]="[tableColumns]" //which is dynamic
#dt2
[rowTrackBy]="trackRecord"
>
<ng-template pTemplate="header">
<tr>
<ng-container *ngFor="let col of tableColumns">
<th [style.width]="col.width">
{{ t(col.name) }}
</th>
</ng-container>
</tr>
</ng-template>
<ng-template
pTemplate="body"
let-line
let-rowIndex="rowIndex"
>
<tr>
<ng-container *ngFor="let col of tableColumns">
<td
[style.width]="col.width"
[pEditableColumn]="col.field"
>
<ng-container
*ngIf="
isNumberField(
line[col.field],
col.field
);
else nonEditable
"
>
<p-cellEditor>
<ng-template pTemplate="input">
<ng-container
*ngIf="
isDateField(
line[col.field],
col.field
);
else textInput
"
>
<p-calendar
[(ngModel)]="
line[col.field]
"
dateFormat="yy-mm-dd"
class="p-inputtext-sm"
style="width: 100%"
></p-calendar>
</ng-container>
<ng-template #textInput>
<input
pInputText
[(ngModel)]="
line[col.field]
"
class="p-inputtext-sm"
pKeyFilter="num"
[style.font-size]="
'0.75rem'
"
[style.font-weight]="
'500'
"
style="float: right"
/>
</ng-template>
</ng-template>
<ng-template pTemplate="output">
<span
[ngStyle]="{
'font-size': '0.75rem',
'font-weight': '500',
float: isNumeric(
line[col.field]
)
? 'right'
: 'none'
}"
>
{{
formatValue(
line[col.field],
col.field
)
}}
</span>
</ng-template>
</p-cellEditor>
</ng-container>
<ng-template #nonEditable>
<span
[ngStyle]="{
'font-size': '0.75rem',
'font-weight': '500',
float: isNumeric(
line[col.field]
)
? 'right'
: 'none'
}"
>
{{
formatValue(
line[col.field],
col.field
)
}}
</span>
</ng-template>
</td>
</ng-container>
</tr>
</ng-template>
</p-table>
一切正常,直到我选择要编辑的数字类型的单元格,当键入任何符号时,我会失去对输入的焦点,并且该输入无法再次获得焦点。 控制台中没有错误,搜索后我希望 trackBy 可以解决问题。但它对我不起作用。
我想问题是,当你更改一个单元格时,Angular“尝试重新绘制”所有表格(抱歉,我没有时间检查并使用 p 表创建 stackblitz)。
您可以在 *ngFor 中使用 track by 或迭代不同的变量
<ng-container *ngFor="let col of tableColumns;trackBy:trackByIndex">
trackByIndex(index: number, item: any): number {
return index;
}
实际上,您可以通过列的某些特定属性进行跟踪,我选择“通用”跟踪