Skip to content Skip to sidebar Skip to footer

Adding Dynamic Row In Table, But It Is Emptying Data In The Row

What am I doing wrong here. Need help. When I click on 'Add' button, the data I selected in the rows of table are becoming blank. But When I select Delete button and then click on

Solution 1:

Ok, solve the problem:-

The main problem is in name="" attribute. name="" must differ in each row .We can solve it in two ways:

1) Either Change the name="" attributes name dynamically so that for every row it has a different name, i did it to add index number with it as

<input [(ngModel)]="notification.notificationLevel" name="notificationThreshold{{i}}" required class="form-control"type="text" />

2) Or avoid name="" and so We can avoid [(ngModel)] By [value] and (input) and can use as like :-

 <input [value]="notification.notificationLevel" (input)="notification.notificationLevel=$event.target.value" required class="form-control"type="text"/>

Solution 2:

In fact, all of your notificationArray elements is the same instance of newNotification. By doing this : this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""}; you actually reset the first line too because of it.

Try to store newNotification in a var instead :

notificationArray: Array<NotificationLevel> = [];
newNotification: any = {};
ngOnInit(): void {
    var newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
    this.notificationArray.push(newNotification);
}
addNotification(index) {
    console.log(this.notificationArray);
    // here is the correctionvar newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
    this.notificationArray.push(newNotification);
    console.log(this.notificationArray);
    returntrue;
}

deleteNotification(index) {
    if(this.notificationArray.length ==1) {
        alert("At least one Notification Required for an Inspection");
        returnfalse;
    } else {
        this.notificationArray.splice(index, 1);
        returntrue;
    }
}

update :

I don't know if it's related but you'll have duplicate threshold id on your select. Use your i to make it unique. It's the same for your input names. You should add [] after the field name otherwise only the last row will be submit.

I added a console.log of you array after the push. Can you tell in comment if the first index is reset at this point ?

Solution 3:

Of course the row is cleared because you are clearing it:

this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""};

So on clicking the add button, the bound values are overridden and then you are pushing it into the array. Thus they are cleared :)

Post a Comment for "Adding Dynamic Row In Table, But It Is Emptying Data In The Row"