I am currently working on an Angular 8 app and I've encountered an issue with data-binding.
The problem arises when trying to edit a specific entry in a table containing data. In the app.component.html file, I have the following code:
<table>
<tr *ngFor="let entry of entries">
<th>{{ entry.asset }}</th>
<th>{{ entry.model }}</th>
<th>{{ entry.ip }}</th>
<th>
<a (click)="editIconPressed(entry)"><i class="material-icons">create</i></a>
</th>
</tr>
</table>
In the app.component.ts file, there is a corresponding function:
editIconPressed(entry: Entry): void {
this.edittedEntry = entry;
this.showEditModal = true;
}
When the user clicks on the edit icon, a modal opens up allowing them to edit the selected entry. The modal implementation is within the same app.component.html file.
<div class="modal" [style.display]="showEditModal ? 'block' : 'none'">
<div class="modal-content edit-entry-modal-width">
<form #editEntryForm="ngForm">
<input class="edit-entry-form-input-field" type="text" [(ngModel)]="edittedEntry.asset" name="model">
<input class="edit-entry-form-input-field" type="text" [(ngModel)]="edittedEntry.model" name="serial">
<input class="edit-entry-form-input-field" type="text" [(ngModel)]="edittedEntry.ip" name="serial">
<button class="btn btn-success" type="submit" (click)="editEntrySaveBtnPressed()">Save</button>
</form>
<button class="btn btn-primary" (click)="closeModal()">Cancel</button>
</div>
</div>
Thanks to two-way data-binding, any edits made in the form inside the modal reflect directly on the table entry being edited. Upon clicking the "Save" button, the editEntrySaveBtnPressed()
function gets triggered, updating both the database and the template table.
If the user decides to cancel the editing process by clicking the "Cancel" button, the closeModal()
function closes the modal. However, it seems that the changes are still reflected in the table even after cancellation.
editEntrySaveBtnPressed(): void {
this.entryService
.editEntry(this.edittedEntry)
.subscribe(res => {
this.edittedEntry = { _id: '', asset: '', model: '', ip: '' };
this.showSuccessMsgForEdit = true;
setTimeout(() => { this.closeModal(); } , 2000);
}, err => {
this.errorMsg = err;
this.showErrorMsg = true;
});
}
closeModal(): void {
this.edittedEntry = { _id: '', asset: '', model: '', ip: '' };
this.showEditModal = false;
}
Any suggestions on why the table in the template doesn't revert back to its original state upon cancellation?
Appreciate your assistance!