-2

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>
3
  • 1
    Your question isn't clear at the moment. "I want to capture all those values inside the input field" - what exactly do you want to do here? Do you want to access values from all the input fields inside the submit() event handler when the button is clicked? Commented Jan 26, 2022 at 15:20
  • I have an input field where user can enter number and I want to use that entered number and pass it to an API. So to pass it to an api I need to get the entered value details first. Hope this is clear? @MichaelD Commented Jan 26, 2022 at 15:23
  • Look into angular.io/guide/forms-overview Commented Jan 26, 2022 at 15:37

1 Answer 1

2

Your current solution does not have any sort of form manager. There are two solutions:

Reactive Forms

// 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

NgModel

// 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.