Reputation: 435
In my angular app, I have 3 inputs say - code, name and price with Add more button at end of the table, when clicking on Add More button there should be a duplication of the row. All this is working fine, but I need to fetch the value of this dynamic box value.
Below is the code table:
<form class="form-horizontal" (ngSubmit)="Data(addForm)" [formGroup]="addForm">
<tr *ngFor="let field of fieldArray; let i = index">
<td><input type="text"formControlName="codeTxt"></td>
<td><input type="text"formControlName="nameTxt"></td>
<td><input type="text"formControlName="priceTxt"></td>
<td><button (click)="deleteFieldValue(i)">Delete</button></td>
<tr>
<tr>
<td><input type="text"formControlName="codeTxt"></td>
<td><input type="text"formControlName="nameTxt"></td>
<td><input type="text"formControlName="priceTxt"></td>
<td><button (click)="addFieldValue()">Add</button></td>
<tr>
</form>
I need to get the value of all the dynamically added row in angular with a total price
Upvotes: 0
Views: 3659
Reputation: 5224
There is probably a better solution using angular binding, but below is "a" quick solution based on javascript and html.
I added a name attribute to your input elements, and modified your addFieldValue function.
function addFieldValue(el){
/**
YOUR PREVIOUS CODE
**/
// container of the data you want, you can add it to a list for example
elementToAdd = {codeTxt: null, nameTxt: null, priceTxt: null };
// get parent tr element
let tr = el.parentNode.parentNode;
// get information from inputs
for(let input of tr.getElementsByTagName('input')){
elementToAdd[input.name] = input.value;
}
console.log(elementToAdd); // you should have all the data here
}
<tr>
<td><input type="text" formControlName="codeTxt" name="codeTxt"></td>
<td><input type="text" formControlName="nameTxt" name="nameTxt"></td>
<td><input type="text" formControlName="priceTxt" name="priceTxt"></td>
<td><button (click)="addFieldValue(this)">Add</button></td>
<tr>
Side Note: in Angular, you have to take care of some security issues. It's probably cleaner to use ElementRef methods. For more info : How to get dom element in angular 2
Upvotes: 1
Reputation: 353
You can bind the value of an input element using NgModel and a template variable (please refer to Two-way data binding with ngModel in the official documentation). In your component, expose 'code', 'name' and 'price' and bind them to the input elements in the template. If you wish to add dynamic rows, iterate on the collection of code, name and price objects and render the table rows using NgFor.
Upvotes: 1