I have an Array with defined answers for a survey-question in data model in component.ts of relevant template.
The template rendering for a <li>
-tag for each answer (in Array) with iteration of this Array via *ngFor-Directive works great.
Now I want to implement a click-event for toggle an active-state for EACH of this <li>
-tags (multiple-choise answer).
The following markup makes all items of the Array (all answers) active, NOT only the single li
-tag, which I have clicked. That's my problem,where I am looking forward to solve it with the support of the community.
HTML-template
<ul>
<li *ngFor="let answer of questions.quest_1.answers, let i=index;" (click)="isActive = !isActive" [ngClass]="{'active': isActive}">{{answer}}</li>
</ul>
relevant component Code
questions = {
quest_1: {
quest: 'my question...',
answers: ['answer A', 'answer B', 'answer C', 'answer D'],
},}
for toggle:
isActive: boolean = false;
I tried to implement the index on click-event in HTML, but it doesn´t works too. Thanks in advance
if you want for Implement a click-event for toggle an active-state for EACH of this <li>-tag
you need to modify you array setting a property active to every item for example:
questions = {
quest_1: {
quest: 'my question...',
answers: [
{text: 'answer A', active: false},
{text: 'answer B', active: false},
{text: 'answer C', active: false},
{text: 'answer D', active: false}
],
}
}
and for the html:
<ul>
<li *ngFor="let answer of questions.quest_1.answers, let i=index;" (click)="answer.active = !answer.active" [ngClass]="{'active': answer.active}">{{answer.text}}</li>
</ul>