Search code examples
angularangular7

how to add rows to a table in angular?


i have this table that uses data from a JSON file, how do i add a function that allows the user to enter data into text fields and add that data into the table?

this is a simple preview of what i have, it displays the data in the JSON in a table

<table>
    <th> Name </th>
    <th> ID </th>
    <th> Job </th>

    <tr *ngFor="let emp of employe">
        <td>{{emp.empName}}</td>
        <td>{{emp.empId}}</td>
        <td>{{emp.empJob}}</td>
    </tr>
</table>

Name: <input type="text">
ID:   <input type="text">
Job:  <input type="text">

<button> Add </button>

note: i don't want to add to the JSON file (i know it's not possible), just the table


Solution

  • You simply have to add button click handler addHandler() which will then insert new element in the array employee and simply bind this array to your table. So everytime you press add button with new data in the input fields new entry will be added to your table employee.

    .ts file

     name = ''; 
     id = '';
     job = '';
     employee = [];
     addHandler(){
     this.employee.push({
            empName:this.name,
            empId:this.id,
            empJob:this.job
      })
     }
    

    .html file

    <table>
    <th> Name    </th>
    <th> ID    </th>
    <th> Job    </th>
    
    <tr *ngFor="let emp of employee">
        <td>{{emp.empName}}</td>
        <td>{{emp.empId}}</td>
        <td>{{emp.empJob}}</td>
    </tr>
    </table>
    
    <br><br>
    
    Name: <input type="text" [(ngModel)]="name"><br>
    ID:   <input type="text" [(ngModel)]="id"><br>
    Job:  <input type="text" [(ngModel)]="job"><br>
    
    <button (click)="addHandler()"> Add </button>
    

    Working demo : link