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?
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;
}
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.