Add And Delete Row Based On Count

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

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

<div class="w-50">
  <h2>Add And Delete Row Based On Count</h2>
  <input class="mt-2" name="number" [(ngModel)]="count" />
  <table class="mt-3">
    <thead>
      <tr>
        <td style="width: 100px;"><label>Action</label></td>
        <td style="width: 120px;"><label>First Name</label></td>
        <td style="width: 120px;"><label>Last Name</label></td>
        <td style="width: 420px;"><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>
      <tr>
        <td>
          <button class="btn btn-success m-2" (click)="addRow()">Add</button>
        </td>
      </tr>
    </tbody>
  </table>
</div>

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() { }

  ngOnInit(): void {
  }

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

  addRow() {
    for (let i = 1; i <= this.count; i++) {
      this.dynamicArray.push(`<td>${i}</td>`)
    }
  }
  deleteRow(index: any) {
    this.dynamicArray.splice(index, 1);
  }

}

output :

Submit a Comment

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

Subscribe

Select Categories