Reputation: 302
I'm currently working on an app that allows users to answer questions about themselves. I'm retrieving these questions from an API. Now, I want to create a form with these questions as the inputs. I'm currently using something similar to the simple form described here: http://learnangular2.com/forms/
Now, I'm wondering if it's possible to create this form based on the questions my API serves. I can get a JSON object with all the questions, but is it possible to create a for loop that populates the form with the questions in the JSON object? This part of the code in the example above gives me the impression that it is not possible this way:
this.loginForm = fb.group({
email: ["", Validators.required],
password: ["", Validators.required]
});
Upvotes: 0
Views: 624
Reputation: 8308
Use ngFor
to loop thru questions and create ngControl
for each.
ngControl
names will be set to Question1
, Question2
...
<form #form="ngForm" (ngSubmit)="logForm(form.value)">
<div *ngFor="#question of questionsList; #i = index">
<label>{{question}}</label>
<input type="text" [ngControl]="'Question' + i">
</div>
<button type="submit">Submit</button>
</form>
logForm
method, inside corresponding component, will get object containing key (ngControl
name) and value (corresponding input value)
Upvotes: 2