27

In my angular app, I have 3 inputs say - code, name and price. And there is a table that displays the user selection. enter image description here

When I click on the add button, the selection from the dropdown should get populated to the table as,

Product     Price      Action
124578-ABC  100        <Delete Button>

When I click on the delete button, the corresponding row should get deleted. I tried doing this using jquery. But I want to know the angular way of doing it.

8
  • 2
    create an array where new object will be pushed after add is clicked and show this array in html using *ngFor Commented Oct 4, 2017 at 10:14
  • if you use angular, the less jquery you have, the better it is. also a little bit of html code is welcome Commented Oct 4, 2017 at 10:15
  • Make use of the idea that porgo gave or else move to reactive forms Commented Oct 4, 2017 at 10:18
  • did you resolve this ? Commented Oct 4, 2017 at 10:28
  • To display data, push it to an observable in the controller side. Bind that observable to display your data. To delete, remove from the observable being used to display the table below and rebind. porgo is correct. Since data is not coming from database, use an array. That will work too. Commented Oct 4, 2017 at 10:31

3 Answers 3

63

Try like this :

In this example i just used textbox instead of your input types

table like

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Code</th>
            <th>Name</th>
            <th>Price</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let field of fieldArray; let i = index">
            <td>
                <input [(ngModel)]="field.code" class="form-control" type="text" name="{{field.code}}" />
            </td>
            <td>
                <input [(ngModel)]="field.name" class="form-control" type="text" name="{{field.name}}" />
            </td>
            <td>
                <input [(ngModel)]="field.price" class="form-control" type="text" name="{{field.price}}" />
            </td>
            <td>
                <button class="btn btn-default"  type="button" (click)="deleteFieldValue(i)">Delete</button>
            </td>
        </tr>
        <tr>
            <td>
                <input class="form-control" type="text" id="newAttributeCode" [(ngModel)]="newAttribute.code" name="newAttributeCode" />
            </td>
            <td>
                <input class="form-control" type="text" id="newAttributeName" [(ngModel)]="newAttribute.name" name="newAttributeName" />
            </td>
            <td>
                <input class="form-control" type="text" id="newAttributePrice" [(ngModel)]="newAttribute.price" name="newAttributePrice" />
            </td>
            <td>
                <button class="btn btn-default" type="button" (click)="addFieldValue()">Add</button>
            </td>
        </tr>
    </tbody>
</table>

typescript sample :

export class Component {
    private fieldArray: Array<any> = [];
    private newAttribute: any = {};

    addFieldValue() {
        this.fieldArray.push(this.newAttribute)
        this.newAttribute = {};
    }

    deleteFieldValue(index) {
        this.fieldArray.splice(index, 1);
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

@Candru Thanks, it worked like a charm. But what can be done if fieldArray is initially null so that there is an empty text box is present in the row
@AbhishekEkaanth I know it is too late. But may be helpful for someone else. You can add the two lines of code which is inside addFieldValue() method inside your ngOnInit() method. Like this ngOnInit(): void { this.fieldArray.push(this.newAttribute) this.newAttribute = {}; }
@Chandru When I click on Add button and enter/select values in the row and then I click again on Add button to input values, it erases all the values which I entered/selected in the first row. Do you know how to resolve this?
@Chandru I tried to implement your idea in my project. I have an issues. wondering if you can help me. ~Sudhir stackoverflow.com/questions/50723261/…
@Chandru, what if I want to add a field in the very beginning of the table?
|
1

Try this:

grid-view-component.html

<div class="container" style="margin-top: 5%">    
        <table class="table table-striped table-bordered">    
            <thead>    
                <tr>    
                    <th>Action</th>    
                    <th>Nmae</th>    
                    <th>Email</th>    
                    <th>Phone</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].name" class="form-control" type="text" />    
                    </td>    
                    <td>    
                      <input [(ngModel)]="dynamicArray[i].email" class="form-control" type="email" />    
                    </td>    
                    <td>    
                      <input [(ngModel)]="dynamicArray[i].phone" class="form-control" type="number"/>    
                    </td>    
                </tr>    
                <tr>    
                  <td (click)="addRow()">    
                    <i class="fa fa-plus fa-2x"></i>    
                  </td>    
                </tr>    
            </tbody>    
        </table>    
</div>  

grid-view-component.ts

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

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

      constructor(private toastr: ToastrService) { }  

      dynamicArray: Array<DynamicGrid> = [];  
      newDynamic: any = {}; 

      ngOnInit(): void {  
          this.newDynamic = {name: "", email: "",phone:""};  
          this.dynamicArray.push(this.newDynamic);  
      }  

      addRow() {    
        this.newDynamic = {name: "", email: "",phone:""};  
          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;  
          }  
      }
} 

grid.model.ts

export class DynamicGrid{     
    name:string;  
    email:string;  
    phone:string;  
}

Comments

-10

Just add two row with same field. one with same field will avoid fieldArray initially null and one with same Field for *ngFor like this

<table>

<tr>
</tr>

<tr *ngFor>
</tr>

</table>

1 Comment

Welcome to Stack Overflow. Please consider the other existing and accepted answer, and explain how yours add new information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.