1

I need to mix the answers to Quiz-Questions in random order.

I have Question objects like:

Question = {
    question: 'what is the capital of Germany?',
    answer1: 'Berlin',
    answer2: 'London',
    answer3: 'Paris',
    answer4: 'Rome'
}

Every time I display the Question in the template I generate a random array e.g.

randomOrder = [3,2,0,1]

I want to use string interpolation in the template to show the question with random Order of the answers:

Question: {{Question.question}}<br>
Answer1: {{Question.answer'answerOrder[0]'}}<br>
Answer2: {{Question.answer'answerOrder[1]'}}<br>
Answer3: {{Question.answer'answerOrder[2]'}}<br>
Answer4: {{Question.answer'answerOrder[3]'}}<br>

Can someone help me with the correct syntax for angular?

2 Answers 2

1

A better aproach is to get a method to return the composed string, using string interpolation, like for example:

questionString(n: number): string {
   return `Answer${n+1}: ${questions['answer'+n]}`;
}

And use, for example:

{{question(1)}}
{{question(2)}}
...

Or better than, inside a for a loop.

Sign up to request clarification or add additional context in comments.

Comments

1

Just refer to object by a dynamic key;

Question: {{Question.question}}
Answer1: {{Question['answer'+answerOrder[0]]}}
Answer2: {{Question['answer'+answerOrder[1]]}}

Or you could store answers as array like this: {question: '...', answers: [a,b,c,d]}

1 Comment

Thanks, this is exactly the syntax I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.