我有一个表格,我想通过点击事件处理程序将表格单元格的 HTMLElement 传递给组件。一开始我有指向正确表格单元格的指针,但是在我手动初始化更改检测后,指针指向错误的单元格(正确单元格的旁边)
我不知道为什么会这样。我在console.log(tableCell)
更改检测初始化之前和之后创建了示例(setEditMode
中的方法AppComponent
)
https://stackblitz.com/edit/angular-module-sandbox-btszav?file=src/app/app.component.html
app.component.html
<button (click)="showClipboardText()">Fill the table</button>
<table id="table" (click)="showTarget($event)">
<thead>
<tr>
<th *ngFor="let colName of colNames">
{{ colName }}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let rowData of data; let rowIndex = index">
<td
#tableCell
*ngFor="
let cellData of rowData.length
? rowData
: [].constructor(colNames.length);
let colIndex = index
"
[attr.data-col-name]="colNames[colIndex]"
(click)="setEditMode(rowIndex, colIndex, tableCell)"
>
{{ cellData?.value }}
<input
type="text"
(keydown)="saveEdit($event, rowIndex, colIndex)"
(blur)="saveEdit($event, rowIndex, colIndex)"
*ngIf="!!data[rowIndex][colIndex]?.isEditMode"
/>
</td>
<button (click)="addRow()">+</button>
</tr>
</tbody>
</table>
app.component.ts
import {
ChangeDetectorRef,
Component,
ElementRef,
QueryList,
ViewChildren,
} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
@ViewChildren('tableCell', { read: ElementRef })
tableCells: QueryList<ElementRef>;
colNames = ['Client', 'Order', 'Total'];
data: Array<Array<{ isEditMode?: boolean; value?: string }>> = [
Array(this.colNames.length),
];
activeCell: { row: number; col: number };
constructor(private cd: ChangeDetectorRef) {}
addRow(): void {
this.data.push(Array(this.colNames.length));
}
setEditMode(row: number, col: number, tableCell: HTMLElement): void {
console.log(tableCell.dataset['colName']);
if (this.activeCell) {
const previousCellData =
this.data[this.activeCell.row][this.activeCell.col];
previousCellData.isEditMode = false;
}
if (!!this.data[row][col]) {
this.data[row][col].isEditMode = true;
this.data[row][col].value = '';
} else {
this.data[row][col] = { ...this.data[row][col], isEditMode: true };
}
this.activeCell = { row, col };
this.cd.detectChanges();
console.log(tableCell.dataset['colName']);
}
saveEdit(event: Event, row: number, col: number): void {
if ((<KeyboardEvent>event).key && (<KeyboardEvent>event).key !== 'Enter')
return;
const value = (<HTMLInputElement>event.target).value;
const previousCellData =
this.data[this.activeCell.row][this.activeCell.col];
previousCellData.isEditMode = false;
this.data[row][col].value = value;
}
}