0

I have a nice simple HTML table with three columns:

 <table >
          <thead>
          <tr>
            <td class="tdBorderEmail"><label>Action</label></td>
            <td class="tdBorderEmail"><label>First Name</label></td>
            <td class="tdBorderEmail"><label>Last Name</label></td>
            <td class="tdBorderEmail"><label>Email</label></td>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let dynamic of dynamicArray; let i = index;">
            <td (click)="deleteRow(i)">
              <i class="fa fa-trash "></i>
            </td>
            <td>
              <input style="width:120px"  name="{{dynamic.firstName}}" [(ngModel)]="dynamic.firstName"  type="text" />
            </td>
            <td>
              <input style="width:120px" name="{{dynamic.lastName}}" [(ngModel)]="dynamic.lastName"  type="text" />
            </td>
            <td>
              <input  style="width:250px" name="{{dynamic.emailAddress}}" [(ngModel)]="dynamic.emailAddress"  type="email"/>
            </td>
          </tr>
          <tr>
            <td (click)="addRow()">
              <i class="fa fa-plus "></i>
            </td>
          </tr>
          </tbody>
        </table>

It displays fine on opening, I can enter the three fields of data, and looking at the angular code in the TS file, I can see the populated values. yet when I add a new row using the following code:

addRow() {
this.newDynamic = {firstName: "", lastName: "",emailAddress:""};
this.dynamicArray.push(this.newDynamic);
console.log('New row added successfully', 'New Row');

}

It blanks the values in the all previous rows. When I look at the values in the TS file, it's properly populated. It just is no longer displayed on the page. Any ideas? I've tried a number of other avenues, even added a .slice() after the add, but nothing seems to help.

Ted Herrlich
  • 159
  • 1
  • 5
  • 13

1 Answers1

1

Your approach is fine. The only thing that can be optimised are,

  1. declare array as empty

    dynamicArray = [];

  2. push new row object directly to array

    this.dynamicArray.push({firstName: "", lastName: "",emailAddress:""});

Here is the working example,

https://stackblitz.com/edit/angular-ivy-6bt4hk?file=src/app/app.component.ts

Narayanan Ramanathan
  • 1,310
  • 10
  • 18
  • Sort of works, the display is showing the values entered into the input fields; however, the underlying array is showing blank strings. When I try and process further, the blanks ("") are the only thing being passed. I am really scratching my head and I cannot afford to lose more hair. thanks for trying. – Ted Herrlich Aug 31 '21 at 21:56
  • if you try to access dynamicArray you should be able to get the input values. Updated the stackblitz example to display the updated values. I guess you are trying to access the data from newDynamic. – Narayanan Ramanathan Aug 31 '21 at 22:03