0

I'm a beginner in angular and I'm trying to fix a problem in which I can't toggle class on button clicks. It's a quiz app and In true/false question format there are 4 statements and 2 buttons to mark tick or cross against it but can use one active class (either true or false). Now, the logic I've used doesn't remove other class on the click of other button. Any help would be appreciated. Working stack blitz demo: https://stackblitz.com/edit/angular-ivy-4yczgp

component.html

<div class="statement-row"
             *ngFor="let item of qblock.options;let j = index"
             [ngClass]="{'wrong-answer': item.selectedIndex === j,'correct-answer':item.customIndex === j}">
          <div class="statement-question">
            <div class="qitem-text">
              <div class="qitem-textbox">
                <p>{{item.statement}}</p>
              </div>
            </div>
            <div class="ccq">
              <button class="qitem qclose"
                   (click)="item.selectedIndex=j">
                <i class="qitembox qclose-icon"></i>
              </button>
              <button class="qitem qtick"
                   (click)="item.customIndex=j">
                <i class="qitembox qtick-icon"></i>
              </button>
            </div>
          </div>
        </div>

2 Answers 2

1

Your problem is that you are using multiple unrelated conditions for ngClass and eacj click you make that condition correct. So you make two conditions correct. That is why you can't change.

You need to initialize another one when clicking

<button class="qitem qclose"
   (click)="item.selectedIndex=j;item.customIndex=null">
   <i class="qitembox qclose-icon"></i>
 </button>
 <button class="qitem qtick"
     (click)="item.customIndex=j;item.selectedIndex=null">
     <i class="qitembox qtick-icon"></i>
 </button>
Sign up to request clarification or add additional context in comments.

Comments

0

This is another way of doing it.

  1. You set the class of the item.
  2. If its wrong-answer that class will be applied and if its correct-answer that class will apply.
  3. You set the item.class = 'wrong-answer' or item.class='correct-answer' on the respective buttons.

See the stackblitz for it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.