Angular 4: How to dynamically add and delete rows in a table

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

When I click the "Add" button, the selection from the drop-down list should be populated with a table as

Product Price Action 124578-ABC 100 <Delete Button> 

When I click the delete button, the corresponding line should be deleted. I tried to do this using jquery. But I want to know the angular way to do this.

+7
angular
source share
2 answers

Try it like this:

In this example, I just used a text box 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); } } 
+10
source share

Just add two lines with the same field. one with the same field will exclude the field ArrayArray is initially null and one with the same field for * ng

 <table> <tr> </tr> <tr *ngFor> </tr> </table> 
-2
source share

All Articles