简体   繁体   中英

Dynamic String Interpolation for variable output in angular

I need to mix the answers of 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 eg 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}}
Answer1: {{Question.answer'answerOrder[0]'}}
Answer2: {{Question.answer'answerOrder[1]'}}
Answer3: {{Question.answer'answerOrder[2]'}}
Answer4: {{Question.answer'answerOrder[3]'}}

Can someone help me with the correct syntax for angular? Thanks

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]}

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 loop.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM