0

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]
});

1 Answer 1

2

Use Template-Driven forms

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)

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.