FacundoGFlores FacundoGFlores - 1 year ago 113
TypeScript Question

Rendering a dynamic survey

I want an opinion for the following scenario:

I have a survey with questions and answers:

questions: Question[];
answer: Answer[];


export class Question {
idQuestion: string;
question: string;

export class Answer {
idAnswer: string;
answer: string;
idQuestion: string;
type: string; // inputbox - select - etc

Currently I can render questions and answer separately:

<ul *ngFor="let question of questions;">
<a id="{{question.idQuestion}}">{{question.question}}</a>
<ul *ngFor="let answer of answers;">
<a id="{{respuesta.idAnswer}}">{{answer.answer}}</a>

But I want to render it in the way:

question1: answer;
question2: answer;
question3: select;

How can I face the problem? Is there any pattern in Angular2? I want to avoid the hardcoding of the
from the
looping in the question and finding the answer.

Answer Source

Two options from the top of my head:


Either map the question and answer together in TS and then display them using one loop:

let questionsAndAnswers =
    questions.map(question => {question:question, answer: answers.find((answer) => answer.idQuestion === question.idQuestion)})

This will give you an array of tubles containing the answer and quiestion. In html you can then do like so:

<ul *ngFor="let questionTuble of questionsAndAnswers ;">
        <a id="{{question.idQuestion}}">{{questionTuble.question.question}}:{{questionTuble.answer.answer}}</a>

Change model

This is the solution i would properly choose:

Change your question model to include the answer, and remove the questionId from answer. In my opinion this improves read-ability in the html:

<ul *ngFor="let question of questions;">
        <a id="{{question.idQuestion}}">{{question.question}}:{{question.answer.answer}}</a>

And to further improve readability i would re-name the 'question' property of question to text or something similar

(Note, haven't tested these, so there may be some syntax errors)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download