問題描述
模型更改後模板未更新 (Template not updating after model changed)
我遍歷一個包含對象的數組:
<tr *ngFor="let file of files | orderBy: 'id':ascending:true | paginate: {id: 'FilePagination',itemsPerPage: 20, currentPage: p}">
<th [innerHTML]="project.files.indexOf(file)+1" scope="row"></th>
<td><a href="{{file.uri + token}}" target="_blank"><i class="fa"
[class.fa‑file‑audio‑o]="types.audio.includes(file.type)"
[class.fa‑file‑pdf‑o]="types.document.includes(file.type)"></i>{{"
" + file.fullName}}</a>
</td>
<td>{{file.size}}</td>
<td>{{file.timestamp | timeCalc}}</td>
<td *ngIf="adminMode">
<button type="button" (click)="deleteFile(file)"
class="fa fa‑trash‑o btn btn‑link p‑0" title="Löschen"></button>
</td>
</tr>
調用deleteFile方法:
deleteFile(file: File) {
this.loading = true;
this.fileService.deleteFile(file).subscribe(
message => this.information = message,
error => {
this.loading = false;
this.errorMessage = error;
},
() => {
this.files.splice(this.files.indexOf(file), 1);
this.loading = false;
}
)
}
訂閱調用完成後,被刪除的文件不會從視圖中移除。儘管如此,它肯定會從數組中刪除,因為數組中所有文件的索引都發生了變化。以下是顯示奇怪行為的兩個屏幕截圖:
刪除前:
刪除後:
參考解法
方法 1:
You can use filter
to exclude the element you want by an object property and reassign:
this.files = this.files.filter(file => file.id !== fileToRemove.id);
Plunker which is minimable and verifiable: http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5?p=preview
方法 2:
Use project.files
HTML
<tr *ngFor="let file of project.files | orderBy: 'id':ascending:true | paginate: {id: 'FilePagination',itemsPerPage: 20, currentPage: p};">
<th [innerHTML]="project.files.indexOf(file)+1" scope="row"></th>
<td><a href="{{file.uri + token}}" target="_blank"><i class="fa"
[class.fa‑file‑audio‑o]="types.audio.includes(file.type)"
[class.fa‑file‑pdf‑o]="types.document.includes(file.type)"></i>{{"
" + file.fullName}}</a>
</td>
<td>{{file.size}}</td>
<td>{{file.timestamp | timeCalc}}</td>
<td *ngIf="adminMode">
<button type="button" (click)="deleteFile(file)"
class="fa fa‑trash‑o btn btn‑link p‑0" title="Löschen"></button>
</td>
</tr>
Delete function:
deleteFile(file: File) {
this.loading = true;
this.fileService.deleteFile(file).subscribe(
message => this.information = message,
error => {
this.loading = false;
this.errorMessage = error;
},
() => {
this.project.files.splice(file, 1);
this.loading = false;
}
)
}
(by user5423851、silentsod、BendYourTaxes)