Here, we will learn about how we can dynamically add and remove table rows using VueJs.

Step 1: Create New App.
ng new angular-addremove

Step 2: Update ts file.

Add below code in src/app/app.component.ts.

import { Component, OnInit } from '@angular/core';

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

  rows:any = []

  constructor() { }

  ngOnInit(): void {

      this.rows = [{
            name:'',
            email:'',
            mobno:''
      }]
  }

  addRow() {
    let row = {name: "", email: "",mobno:""};
    this.rows.push(row);
 }

 deleteRow(index:any) {

      this.rows.splice(index, 1);
}
submit(){

  console.log(this.rows)
}

}

Step 3: Update html file.

Add below code in src/app/app.component.html.

<h3 class="text-primary" align="center">Add Remove Table Row Dynamically In Angular</h3>
<div class="container">
  <div class="panel-group">
    <div class="panel panel-primary">
        <div class="panel-body">
          <button (click)="addRow()" class="btn btn-primary pull-right" style="cursor: pointer;">Add</button><br>
            <table class="table table-bordered">
            <thead class="text text-primary">
                  <tr>
                      <th>Name</th>
                      <th>Email</th>
                      <th>Mobile Number</th>
                      <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <tr *ngFor="let row of rows; let i = index;">
                     <td>
                       <input [(ngModel)]="rows[i].name" class="form-control" type="text" />
                     </td>
                     <td>
                       <input [(ngModel)]="rows[i].email" class="form-control" type="text" />
                     </td>
                     <td>
                       <input [(ngModel)]="rows[i].mobno" class="form-control" type="text"/>
                     </td>
                     <td><button class="btn btn-danger" (click)="deleteRow(i)" style='cursor: pointer;'>Remove</button></td>
                 </tr>
             </tbody>
            </table>
            <button class="btn btn-info" (click)="submit()">Submit</button>
        </div>
    </div>
    </div>
</div>

The post Add And Remove Table Row Dynamically In Angular. appeared first on PHPFOREVER.

Categories: PHP