I have an input field which is being generated using *ngFor and I want to capture all those values inside the input field on submit button click. I have tried all possible ways but not able to get the entered data, please help me. Below is my code I have tried.
html Code:
arr= [{name:"test", percentage: "29"},{name:"abc", percentage: "45"}, {name:"def", percentage: "63"}]
<div *ngFor= "let obj of arr">
<input type="text" [value]="obj.percentage">
</div>
<button (click)="submit()"></button>
Your current solution does not have any sort of form manager. There are two solutions:
// component.ts
form = new FormGroup( {
test: new FormControl(null)
// Add your other fields here
} );
// Patch your values into the form
arr.forEach(value => {
this.form.get(value.name).patchValue(value.percentage);
})
// html
<div *ngFor= "let obj of arr">
<input type="text" [formControl]="form.get(obj.name)" >
</div>
Your form will store all the values. To get them once, you could use form.value
// component.ts
test: boolean;
// Add your other fields here
// Patch your values into the form
arr.forEach(value => {
this.[value.name] = value.percentage;
})
// html
<div *ngFor= "let obj of arr">
<input type="text" [(ngModel)]="obj.name" >
</div>
Both of these examples are cutting corners but they should give you enough of an idea of where to head next. I'd suggest the Reactive Forms path.