Issue
I have created an editable table following this tutorial - https://mdbootstrap.com/docs/angular/tables/editable/#:~:text=Angular%20Bootstrap%20Editable%20Tables%20are,is%20now%20easier%20and%20quicker.
HTML:
<table class="table" *ngIf="menuFromDb.length>0">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let thing of menuFromDb; let i = index;">
<td contenteditable="true" (keyup)="changeItemName(i, 'itemName', $event)" (blur)="updateItemName(i, 'itemName', $event)">{{thing.itemName}}</td>
<td contenteditable="true" (keyup)="changePrice(i, 'price', $event)" (blur)="updatePrice(i, 'price', $event)">{{thing.price}}
</td>
<td>
<button *ngIf="menuFromDb.length>0" class="pull-right btn btn-danger btn-sm" (click)="deleteExistingItem(i)">Delete This</button>
</td>
</tr>
</tbody>
</table>
...
<div class="bd-highlight">
<button *ngIf="menuFromDb.length>0" class="btn btn-info btn-sm" (click)="addItem()">Add New
</button>
</div>
....
TS:
....
menuFromDb = Array();
editField = "";
editPrice = 0;
....
...
async getMenu()
{
await this.userService.getMenu().then(data=>
{
this.menuFromDb = data;
});
}
....
// update itemName
updateItemName(id: number, property: any, event: any) {
const editField = event.target.textContent;
this.menuFromDb[id][property] = editField;
//console.log("updated itemName:", this.menuFromDb[id][property])
}
changeItemName(id: number, property: any, event: any) {
this.editField = event.target.textContent;
}
// update price
updatePrice(id: number, property: any, event: any) {
const editPrice = event.target.textContent;
this.menuFromDb[id][property] = +editPrice;
}
changePrice(id: number, property: any, event: any) {
this.editPrice = +event.target.textContent;
}
addItem()
{
this.menuFromDb.push({itemName: '', price: 0, quantity: 0, amount: 0});
}
View:
The problem is: When I enter any data in the Item column it is getting repeated.
For example, I entered df
but it changed to dfdf
instantly when I leave the column. It happens for first time for newly added row only. If I again change it to another value then it works fine. I am struggling to find the cause, please help.
Solution
I found the solution. You shouldn't use the "placeholder"-style between the td start and closing tags, because you rely on "textContent" in the TS and so it sometimes happens, that Angular adds the value to the content of the Element that the user changed (USER-ADDED {{ thing.itemName }}). Check this in your Chrome Dev Tools, then you will see it as "dt" " dt ".
Check this StackBlitz: https://stackblitz.com/edit/angular-ivy-hkbz89?file=src%2Fapp%2Fapp.component.html
I used the [textContent]-Attribute and cleared the contents of the TDs.
Answered By - Kevin Glier
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.