How to get the table input values and create key value in Angular

Viewed 36

Hi what i am trying is i am trying to create a dynamic table with input using row span here

requirement:

I have 2 fields in the table username & email * inputs . I can enter what ever text i want inputs. after that when ever i press getTableValue button then i need to retrieve all the inputs values and along with that corresponding username value and i need to create json here username will be the key and what ever i enter in that input will be the values.

enter image description here suppose my username is bret and in the input i entered avenger and in json it needs to be

{
  "bret":"avenger"
}

I tried the reactive form but unable to get the values below is my code

<div>
  <button type="button" (click)="getTableValue()">Get Value </button>
  <table class="table table-bordered table-striped">
    <thead>
      <tr>
        <th>username</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let data of dynamicData; let i = index">
        <td>{{ data.username }}</td>
        <td>{{ data.email }}</td>
        <td [attr.rowspan]="5" *ngIf="i % 5 == 0">
          <input type="text" />
        </td>
      </tr>
    </tbody>
  </table>
</div>

below is my stackblitz url ==> https://stackblitz.com/edit/angular-ivy-drfozo?file=src/app/app.component.ts

1 Answers

You can add the ngModel in the field

<td [attr.rowspan]="5" *ngIf="i % 5 == 0">
   <input type="text"  [(ngModel)]="data[ data.username.toLowerCase() ]"/>
</td>

This is return in console.log

0: Object
  bret: "test"
  email: "Sincere@april.biz"
  id: 1
  name: "Leanne Graham"
  username: "Bret"
__proto__: Object
1: Object
  email: "Shanna@melissa.tv"
  id: 2
  name: "Ervin Howell"
  username: "Bret"
__proto__: Object
2: Object
  email: "Nathan@yesenia.net"
  id: 3
  name: "Clementine Bauch"
  username: "Bret"
__proto__: Object
3: Object
  email: "Julianne.OConner@kory.org"
  id: 4
  name: "Patricia Lebsack"
  username: "Bret"
__proto__: Object
4: Object
  email: "Lucio_Hettinger@annie.ca"
  id: 5
  name: "Chelsey Dietrich"
  username: "Bret"
__proto__: Object
5: Object
  delphine: "test1"
  email: "Karley_Dach@jasper.info"
  id: 6
  name: "Mrs. Dennis Schulist"
  username: "Delphine"
__proto__: Object
6: Object
  email: "Telly.Hoeger@billy.biz"
  id: 7
  name: "Kurtis Weissnat"
  username: "Delphine"
__proto__: Object
7: Object
  email: "Sherwood@rosamond.me"
  id: 8
  name: "Nicholas Runolfsdottir V"
  username: "Delphine"
__proto__: Object
8: Object
  email: "Chaim_McDermott@dana.io"
  id: 9
  name: "Glenna Reichert"
  username: "Delphine"
__proto__: Object
9: Object
  email: "Rey.Padberg@karina.biz"
  id: 10
  name: "Clementina DuBuque"
  username: "Delphine"

[UPDATE]

If you want only these updated values

You can get like this:

const yourData = this.dynamicData.filter(d => Object.keys(d).length == 5)

I hope it helps

Here is demo

Related