Reputation: 13
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?
Upvotes: 1
Views: 1038
Reputation: 12011
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]}
Upvotes: 1
Reputation: 2614
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.
Upvotes: 1