How To Dynamically Add And Delete Rows In A Table In Angular

How To Dynamically Add And Delete Rows In A Table In Angular

In this article, we will learn about how to dynamically add and delete rows in a table in an angular application.

So let's start with the implementation,

First, we need to create a new angular application using the following command.

ng new dynamic-table

Now, we need to install Bootstrap for table design.

npm install bootstrap

Now, we need to also install Toaster for we use action notification messages.

npm install ngx-toastr --save

Now we need to bootstrap and toaster CSS file references into the angular.json file.

How To Dynamically Add And Delete Rows In A Table In Angular

Now, we need to create a class for the grid namely as grid.model using the following command.

ng g class grid.model

Installation and project setup are complete. Now, we are going to implement the logic of dynamically adding and deleting rows in a table in the angular application.

Add the references into the app.module.ts file using the following code.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ToastrModule } from 'ngx-toastr';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule ,
    BrowserAnimationsModule,
    ToastrModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, Open the index.html file and add the font-awesome reference using the following code.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>DynamicGrid</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Now, we need to create a model class into the grid.model.ts for the grid using following the code.

export class DynamicGrid{   
    title1:string;
    title2:string;
    title3:string;
}

Now add the following code under the app.component.html file.

<div class="container" style="margin-top: 5%">
  <table class="table table-striped table-bordered">
  	<thead>
  		<tr>
  			<th>Action</th>
  			<th>Title 1</th>
  			<th>Title 2</th>
  			<th>Title 3</th>
  		</tr>
  	</thead>
  	<tbody>
  		<tr *ngFor="let dynamic of dynamicArray; let i = index;">
  		<td (click)="deleteRow(i)">
  			<i class="fa fa-trash fa-2x"></i>
  		</td>
  			<td>
  			<input [(ngModel)]="dynamicArray[i].title1" class="form-control" type="text" />
  			</td>
  			<td>
  			<input [(ngModel)]="dynamicArray[i].title2" class="form-control" type="text" />
  			</td>
  			<td>
  			<input [(ngModel)]="dynamicArray[i].title3" class="form-control" type="text"/>
  			</td>
  		</tr>
  		<tr>
  		<td (click)="addRow(i)">
  			<i class="fa fa-plus fa-2x"></i>
  		</td>
  		</tr>
  	</tbody>
  </table>
</div>

Now add the following code under the app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { DynamicGrid } from 'grid.model';

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

  constructor(private toastr: ToastrService) { }

  dynamicArray: Array<DynamicGrid> = [];
  newDynamic: any = {};
  ngOnInit(): void {
      this.newDynamic = {title1: "", title2: "",title3:""};
      this.dynamicArray.push(this.newDynamic);
  }

  addRow(index) {  
      this.newDynamic = {title1: "", title2: "",title3:""};
      this.dynamicArray.push(this.newDynamic);
      this.toastr.success('New row added successfully', 'New Row');
      console.log(this.dynamicArray);
      return true;
  }
  
  deleteRow(index) {
      if(this.dynamicArray.length ==1) {
        this.toastr.error("Can't delete the row when there is only one row", 'Warning');
          return false;
      } else {
          this.dynamicArray.splice(index, 1);
          this.toastr.warning('Row deleted successfully', 'Delete row');
          return true;
      }
  }

}

Now, run the application using the ng serve command and see the browser screen. now we are able to dynamically add and delete rows in a table.

Conclusion

In this article, we learned how to dynamically add and delete rows in a table in an angular application.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post