0
votes

Is it possible to create independent child Components from ngFor iteration in Angular 2?

I'm making a Quiz application with a structure, where one Quiz component have multiple Categories, and one Category have multiple Questions.

Angular will generate a form from Quiz retrieved from REST api, where user can navigate back and forth between different categories of questions and finally save partial or submit complete form.

I sketched the following pseudo-structure for application template:

<html>
  <form>
    <category>
      <question *ngFor="let question of questions" />
    <category>
    <navigate/>
  </form>
</html>

Quiz component has a list of categories and a reference to an active category. Category component has input binding to reflect the active category of Quiz. Category has list of Questions, which I want to encapsulate in distinct Component. Thus I iterate through the list of questions and create question tag.

Now the problem is, how I populate the Question component for each tag according the question object creating that tag? Is this possible, or should I merge the question template with Category?

3
will you be to able to help me on the query that I posted?stackoverflow.com/questions/54016062/… Our questions looks similar. I guess you would have gone through similar kind of issues.Renjith

3 Answers

3
votes

Pass the question object into the Question component using an input property. Let's name that input property qObj:

<question *ngFor="let questionObj of questions" [qObj]="questionObj"></question>

In your Question component, declare the input property:

import {Component, Input} from '@angular/core';
@Component({ 
   selector: 'question',
   template: `<div>{{qObj.question}}`  // I'm assuming it has a question property
})
export class Question {
   @Input() qObj:Object;
}
0
votes

Your question is a bit vague. it seems to me that your category component needs to get from the server list of questions with the ngOnInit hook.

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

-1
votes

I'm not sure if I completely understand your question but if your category has the list of questions you should make your ngFor or I suggest ng-repeat in the category

<html>
  <form>
    <category ng-repeat="question in $ctrl.questions">
      <question/>
    <category>
    <navigate/>
  </form>
</html>

Where $ctrl should refer to the controller of your category.
You can then use the question variable inside this tag