Rendering a dynamic survey

2019-09-13 12:46发布

问题:

I want an opinion for the following scenario:

I have a survey with questions and answers:

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

Where Question is:

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;">
    <li>
        <a id="{{question.idQuestion}}">{{question.question}}</a>
    </li>
</ul>
<ul *ngFor="let answer of answers;">
    <li>
        <a id="{{respuesta.idAnswer}}">{{answer.answer}}</a>
    </li>
</ul>

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 html from the ts looping in the question and finding the answer.

回答1:

Two options from the top of my head:

Map

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 ;">
    <li>
        <a id="{{question.idQuestion}}">{{questionTuble.question.question}}:{{questionTuble.answer.answer}}</a>
    </li>
</ul>

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;">
    <li>
        <a id="{{question.idQuestion}}">{{question.question}}:{{question.answer.answer}}</a>
    </li>
</ul>

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)