【发布时间】:2017-10-26 02:39:20
【问题描述】:
我有一个 Angular 2 应用程序,它使用 Material 2 table 来显示项目及其数据。我在每一行的右侧都有一个按钮,允许用户编辑该行。这个切换编辑按钮会导致inputs 弹出,并填充该行的值。输入的值使用value="{{row.property}}" 设置。
我可以使用 [(ngModel)]="row.property" 填充 input 的值并将模型绑定到该对象,但我不希望这样,因为我希望用户能够取消更改。如果input绑定到对象,即使用户点击“取消”,模型也会改变。
所以,设置value="{{row.property}}" 是我想要的,但是当我点击“保存”按钮时,我不知道如何检索inputs 的值。
<mat-table #table [dataSource]="dataSource" matSort>
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Season Column -->
<ng-container matColumnDef="season">
<mat-header-cell *matHeaderCellDef class="padding-a-5" mat-sort-header> Season </mat-header-cell>
<mat-cell *matCellDef="let row" class="padding-a-5">
<span *ngIf="!editingRow(row)"> {{row.season}} </span>
<input *ngIf="editingRow(row)" value="{{row.season}}" class="padding-a-5 half-width">
</mat-cell>
</ng-container>
<!-- Item Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef class="mat-column-itemName padding-a-5" mat-sort-header> Item Name </mat-header-cell>
<mat-cell *matCellDef="let row" class="mat-column-itemName">
<span *ngIf="!editingRow(row)"> {{row.name}} </span>
<input *ngIf="editingRow(row)" [(ngModel)]="row.name" class="padding-a-5 half-width">
</mat-cell>
</ng-container>
<!-- Toggle Edit Row Column -->
<ng-container matColumnDef="toggleEdit">
<mat-header-cell *matHeaderCellDef class="mat-column-row-actions"></mat-header-cell>
<mat-cell *matCellDef="let row" class="toggle-edit mat-column-row-actions">
<button *ngIf="!editingRow(row)" mat-button (click)="editRow(row, true)" aria-label="edit">
<mat-icon aria-hidden="true">mode_edit</mat-icon>
</button>
<button *ngIf="editingRow(row)" mat-button (click)="saveRow(row)" aria-label="save">
<mat-icon aria-hidden="true">save</mat-icon>
</button>
<button *ngIf="editingRow(row)" mat-button (click)="editRow(row, false)" aria-label="cancel">
<mat-icon aria-hidden="true">cancel</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
// some of the methods in my Angular 2 component
editingRow(row) {
return this.editRows[row.id];
}
editRow(row, editRow: boolean) {
this.toggleEditMode(row.id, editRow);
}
saveRow(row): void {
this.toggleEditMode(row.id, false);
console.log(row);
// TODO
// save(row);
}
toggleEditMode(rowId: number, editMode: boolean): void {
this.editRows[rowId] = editMode;
}
【问题讨论】: