Monday 8 June 2020

Dynamically Add And Remove Rows In Angular 7|8|9 Part-7



Dynamically Add And Remove Rows In Angular 7|8|9




In this article we will learn about how we can add or remove rows dynamically in angular. I am going to divide the problem into steps, so that you can easily understand and implement it side by side.

Below are the basic prerequisite:

1. Node js should be installed in dev system.
2. Angular CLI should be installed.
3. Any code editor ( i would prefer VS Code).

Please follow all the below steps carefully and try to implement side by side.

Step-1: Open the new Terminal window in the Visual Studio code.
Dynamically Add And Remove Row In Angular 7
Step-2: Type the below command to create the new project . 
  1. ng new dynamic-grid-example  

Step-3: Install the Bootstrap and Toastr, run the below command one after other. 
  1. npm install bootstrap  
  2.    
  3. npm install ngx-toastr --save  
Dynamically Add And Remove Row In Angular 7
Dynamically Add And Remove Row In Angular 7

Step-4: Go to the project directory by the below command: 

   cd dynamic-grid-example 




Step-5: Now create the component class. Run the below command in the terminal window.
  1. ng g c dynamic-grid

Step-6: Add the reference for bootstrap and toaster in the angular.json file.

Step-7: Type the following command to generate the model file for the class. 
  1. ng g class dynamic-grid   

Step-8Open the dynamic-grid.ts file and add the below code.



Step-9: Open the app.module.ts file present in the root folder and add the references there.
you can import ReactiveFormsModue , ToastrModule etc.

Notes: I have create dynamic-grid component inside demo module and injected demo module inside app module. So dynamic-grid component is injected inside demo module in my project, you can create dynamic-grid component inside the app module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModuleHTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsModuleFormsModule } from '@angular/forms';
import { DemoModule } from './demo/demo.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
  declarations: [
    AppComponent,
    Demo2Component 
  ],

  imports: [
    BrowserModule,
    FormsModule
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot(),
    ReactiveFormsModule,
    DemoModule,
    AppRoutingModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORSuseClass: MyInterceptormulti: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step-10: Add the dynamic-grid compoment path into app routing module.



Step-11: Open the index.html file and add the reference for font-awesome. Copy the code with red background and paste into your index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Crud Example</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>


Step-12: Add the below code into dynamic-grid.component.html file.

<h1 style="color:hotpink;text-align: center;">dynamic-grid Example</h1>
<div class="container" style="margin-top: 5%">    
    <table class="table table-striped table-bordered">    
        <thead>    
            <tr>    
                <th>Action</th>    
                <th>Id </th>    
                <th>Name</th>  
                <th>Address</th>    
            </tr>    
        </thead>    
        <tbody>    
             <tr *ngFor="let dynamic of dynamicArray; let i = index;">   
              <td (click)="deleteDynamicRow(i)" style="color: red;">    
               <i class="fa fa-trash fa-2x"></i>    
              </td>    
                <td>    
                  <input [(ngModel)]="dynamicArray[i].column1"  
class="form-control" type="text" />    
               </td>    
                <td>    
                  <input [(ngModel)]="dynamicArray[i].column2"  
class="form-control" type="text" />    
                </td>    
                <td>    
                  <input [(ngModel)]="dynamicArray[i].column3"  
class="form-control" type="text"/>    
                </td>            
            </tr>    
            <tr>    
              <td (click)="addDynamicRow(1)">    
               <i class="fa fa-plus fa-2x" style="color:green;"></i>    
              </td>    
            </tr>    
        </tbody>    
    </table>    
  </div>    

 Step-13: Finally, Add the below code into dynamic-grid.component.ts file.

import { ComponentOnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';  
import { DynamicGrid } from 'src/app/model/dynamic-grid';

@Component({
  selector: 'app-dynamic-grid',
  templateUrl: './dynamic-grid.component.html',
  styleUrls: ['./dynamic-grid.component.scss']
})
export class DynamicGridComponent implements OnInit {  
  constructor(private toastrToastrService) { }  
  dynamicArrayArray<DynamicGrid> = [];  
  newDynamicany = {};  
  ngOnInit(): void {   
    this.newDynamic = {column1: "1"column2: "aryan",column3:"Noida"};
      this.dynamicArray.push(this.newDynamic);  
  }  
  addDynamicRow(index) {   
    this.newDynamic = {column1: "1"column2: "aryan",column3:"Noida"}; 
      this.dynamicArray.push(this.newDynamic);  
      this.toastr.success('Dynamic row added dynamically''New dynamic row');  
      console.log(this.dynamicArray);  
      return true;  
  }  

  deleteDynamicRow(index) {  
      if(this.dynamicArray.length ==1) {  
       this.toastr.error("There is only one row , so cannot be deleted"'Warning');  
          return false;  
      } else {  
          this.dynamicArray.splice(index1);  
          this.toastr.warning('Dynamic row deleted successfully''Delete row action');  
          return true;  
      }  
  }   





You can see the final output:


In this way we learnt how to add or remove rows dynamically in angular. I hope you understood and implemented it in your project.

If you get struck any where or have confusion to understand any of the above steps, please inform me by writing you comment in the comment box, if you are satisfied then also please write some words for me. 

I will come up with some interesting topic very soon !! 


 Thank You 





1 comment:

  1. Please write your feedback in the comment box Thanks !!

    ReplyDelete

In case of any query , please let me know, Thanks