How To Add Or Remove Rows Dynamically In Angular

In this blog we will learn how to add or remove rows dynamically in angular.

Open app.component.ts file and add below code :

import { Component } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor() {

  }

  dynamicArray: any = [];
  newarr: any = []
  newDynamic: any;

  addRow() {
    this.dynamicArray.push({ firstName: '', lastName: '', emailAddress: '' })
  }

  deleteRow(index: any) {
    this.dynamicArray.splice(index, 1);
  }

}

Open app.component.html file and add below code :

<section class="m-5">
  <button class="btn btn-primary" style="width: 5%;" (click)="addRow()">Add</button>
  <table class="w-50 border mt-3">
    <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>
          <button class="btn btn-danger" (click)="deleteRow(i)">Delete</button>
        </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>

    </tbody>
  </table>


  <div class="container mt-5 w-50 m-0">
    <h2 class="text-center">Data Entry</h2>

    <table class="table table-striped mt-3">
      <thead>
        <tr>
          <th>firstName</th>
          <th>lastName</th>
          <th>emailAddress</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let value of dynamicArray">
          <td>{{ value.firstName }}</td>
          <td>{{ value.lastName }}</td>
          <td>{{ value.emailAddress }}</td>
        </tr>
      </tbody>
    </table>
  </div>

</section>

output :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories