我通过将表格行数据传递给它来打开一个带有编辑表单的对话框。当我关闭对话框而不保存编辑内容时,它仍然更改了父html中的表行数据。
这是我的代码示例:
https://stackblitz.com/edit/angular-material2-table-to-dialog-dzy4dh
父HTML页面:
<p>Car List.</p>
<p id="show"></p>
<p id="show1"></p>
具有编辑形式的对话框:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 ">
... ...
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef> Symbol </th>
<td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"
(click)="openDialog(row)"></tr>
</table>
然后我尝试了通过Angular Material2文档示例中的两种方式进行数据绑定的带有编辑表单的对话框。当关闭对话框时,像我想要的那样,不受影响了父html数据:
https://stackblitz.com/edit/angular-arsgs2
父HTML页面:
<div class="basic-container">
<mat-form-field>
<input matInput placeholder="Name" [(ngModel)]="data.name">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Weight" [(ngModel)]="data.weight">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Symbol" [(ngModel)]="data.symbol">
</mat-form-field>
<button mat-button (click)="closeDialog()">Close</button>
</div>
对话框编辑表单页面:
<ol>
<li>
<mat-form-field>
<input matInput [(ngModel)]="animal" placeholder="Your favorite animal?">
</mat-form-field>
</li>
<li>
<button mat-raised-button (click)="openDialog()">Pick one</button>
</li>
<li *ngIf="animal">
You chose: <i>{{animal}}</i>
</li>
</ol>
答案 0 :(得分:1)
尝试这样的事情:
在此处使用_updateChangeSubscription
方法。
app.component.ts:
dialog.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result)
if (result) {
this.dataSource.data[result.position - 1] = result
this.dataSource._updateChangeSubscription();
}
});
sample-dailog.component.html:
<mat-form-field>
<input matInput placeholder="Name" [(ngModel)]="name">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Weight" [(ngModel)]="weight">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Symbol" [(ngModel)]="symbol">
</mat-form-field>
<div mat-dialog-actions>
<button mat-button (click)="closeDialog()">Close</button>
<button mat-button [mat-dialog-close]="{position: data.position, name: name, weight: weight, symbol: symbol}" cdkFocusInitial>Ok</button>
</div>
sample-dailog.component.ts:
name: any;
weight: any;
symbol: any;
constructor(
public dialogRef: MatDialogRef<SampleDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
) {
this.name = this.data.name;
this.weight = this.data.weight;
this.symbol = this.data.symbol;
}
ngOnInit() {
console.log('Dialog got', this.data);
}
closeDialog() {
this.dialogRef.close();
}