Utilizing Angular's classBinding on each individual element through a click event listener

For my school project, I am developing a Quiz App. In the Learning section, I want to implement a feature that changes the color of each answer option when clicked. If the answer is correct, it should turn green; if not, it should turn red. This feature should also be toggleable. I have been struggling for hours with this functionality and feel a bit lost.

Below is the HTML code for my component:

<div class="container p-5 ">
      <div class="row">
        <div class = "col-sm-8 offset-2">
          <p class = "text-center">{{currentQuestion + 1 }} of {{questions.length}} </p>
          <h3>{{questions[currentQuestion].question}}</h3>
          <div  *ngFor="let question of questions[currentQuestion].answers">
            <ul>
              <li (click) = "answerSelected=!answerSelected" [ngClass] = "answerSelected ? 'correct' : 'incorrect'"> {{question.option}}</li>
            </ul>
          </div>

          […]

This is my TypeScript file for the component:


    import { Component, OnInit } from '@angular/core';
    import { QuestionsService } from '../shared/questions.service';
    import { Question } from '../shared/question';

    @Component({
      selector: 'app-question-learn',
      templateUrl: './question-learn.component.html',
      styleUrls: ['./question-learn.component.css']
    })
    export class QuestionLearnComponent implements OnInit {
    questions: Question[] = [];
    
    currentQuestion = 0;
    answerSelected = false;
    correctAnswers = 0;
    incorrectAnswers = 0;

    buttonText = "Show Hint";
    […]

In addition, here is the interface for the Question model:

export interface Question {
  id: number,
  question: string,
  answers: {option: string, correct:boolean}[],
  description: string
}

If you need a visual reference, check out this image link.

Answer №1

It's been a bit of a struggle, but I feel like I've taken a step forward. The classes are bound, but I'm having trouble getting this function to work properly. When clicked, all the answers turn green. I believe the issue lies in binding the question.correct property to my function so that it behaves correctly.

I added a new variable:

colorClass = 'normal';

Here is my function :

onAnswer() {
    let question = this.questions[this.currentQuestion];
    for (let answer of question.answers) {
        if (answer.correct === true  ) {
          this.colorClass = 'correct';
        } else {
          this.colorClass = 'incorrect';
       }
    }
}

html :

<h3>{{questions[currentQuestion].question}}</h3>
      <div  *ngFor="let question of questions[currentQuestion].answers">
        <ul>
          <li [className] ="colorClass"   (click) = "onAnswer()">{{question.option}}</li>
        </ul>
      </div>

My css classes

ul {
  display: flex;
  width: 80%;
  margin: 0;
  padding: 0;
  flex-flow: column;
}

ul li.normal {
  list-style: none;
  line-height: 2;
  border: 1px solid #cdd2d2;
  margin-bottom: 10px;
  border-radius: 15px;
  text-align: center;
  cursor: pointer;
}

li.normal:hover {
  background-color: whitesmoke;
}

li.correct {
  list-style: none;
  line-height: 2;
  border: 1px solid #cdd2d2;
  margin-bottom: 10px;
  border-radius: 15px;
  text-align: center;
  cursor: pointer;
  border: 1px solid green;
  background-color: green;
  color: white;
  font-weight: 600;
}

li.incorrect {
  list-style: none;
  line-height: 2;
  border: 1px solid #cdd2d2;
  margin-bottom: 10px;
  border-radius: 15px;
  text-align: center;
  cursor: pointer;
  border: 1px solid red;
  background-color: red;
  color: white;
  font-weight: 600;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing a child in an existing object with Firebase and Angular 6

How can I save a new form to an existing list with the following code snippet: createNewTumeur(newTumeur: Tumeur) { this.tumeurs.push(newTumeur); const id: string = this.route.snapshot.params['id']; firebase. ...

What is the best way to extract information from a JSON file?

Hello all, I'm facing an issue while trying to parse a JSON object in Angular. I've created a JSON object with all the necessary data in my service. In the component, I am attempting to parse this JSON and display all messages in youSend.mess ...

What is the reason for a high-order generic function to eliminate falsy types from the argument list of the returned function?

Consider this example of a unique Decorator Factory Builder - a builder that constructs Decorator Factories to define metadata for forms: interface FormFieldOptions { name?: string; label?: string; format?: string; } type FormProperties = Record< ...

Npm version error: module 'are-we-there-yet' not found

After updating nodejs from v6.9.2 to V10.16.3, I encountered an issue with running npm install. When checking npm -v, the following error is displayed: Error: cannot find module 'are-we-there-yet' I attempted uninstalling and reinstalling node ...

Encountering an issue with importing a component in a mixin in NuxtJS

Currently, my main technologies are Nuxtjs and Nuxt-property-decorator To prevent repeating a certain method, I created a mixin This method requires the use of a component (Alert component) In order to use the component in the mixin, I imported it Howe ...

angular Struggling with @Input and data interpolation functionality within web components

I have built a collection of web components designed for various Angular projects. To make these components reusable, I am using @angular/elements to convert them into custom elements and then serving them via http-server. One of the components I develope ...

When using Inertia.js with Typescript, an issue arises where the argument types {} and InertiaFormProps{} are not compatible with the parameter type Partial<VisitOptions> or undefined

I set up a brand new Laravel project and integrated Laravel Breeze along with Typescript support. After creating a form (using useForm()) and utilizing the .post() method with one of the options selected (such as onFinish: () =>), I encountered the fol ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

The configuration object is invalid. Webpack has been initialized with a configuration object that does not conform to the API schema

I recently created a basic helloworld react app through an online course, but I encountered the following error: Invalid configuration object. Webpack has been initialized with a configuration object that does not adhere to the API schema. - configur ...

Is there a method to determine the total of values contained within an HTML table under designated headers? - IONIC

Details: My html table has 2 columns labeled as Debit and Credit, each with respective numbers listed below them. Goal: I am looking to calculate the sum of the numbers under both Debit and Credit. Please check out the about page in the repository for ...

encountering difficulties with implementing the custom pagination feature in Angular 2

After creating a custom pagination component using Angular2, I encountered an error when trying to use it in another component: Can't bind to 'offset' since it isn't a known property of 'app-pagination'. Update Made in app. ...

Check if the <ion-content> in Angular Ionic has reached the bottom when scrolling

I'm in the process of developing a messaging app using Angular and Ionic. I want to trigger the scrollToBottom method only when it is scrolled to the very bottom. This way, if someone scrolls to the top to read old messages while their partner sends a ...

What is the process for integrating Angular files into an Express server?

I am trying to figure out how to host Angular files on my Express server. My friend created some web pages using Angular and I have an Express server set up. I have tried searching for a solution online but have not been successful. I have looked at some p ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...

Sending data to templates in Angular 2 using @Input()

I can't seem to figure out what I'm doing wrong with my listing template. I am trying to make it more dynamic by passing parameters using []="" and @Input(). Here is an example: <div class="listing wrapper"> <div class="wrapper" ...

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

Seamlessly incorporating Storybook with Tailwind CSS, Create Next App, and TypeScript

*This is a new question regarding my struggles with integrating Storybook and Tailwind CSS. Despite following the recommended steps, I am unable to make Tailwind work within Storybook. Here's what I've done: I started a TypeScript project from s ...

What is the method for making an interface extension from a type as optional?

Can you help me create an interface that includes all students and part of a school, ensuring that gender is required for Peter and optional for other students? export type School = { address: string; state: string; }; export type Gender = { gender: ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Increase the number of columns in ion-grid to a maximum of 24 columns by customizing the ion-grid columns

Can anyone assist me in achieving an ion-grid with 24 columns? I was researching the Ionic page (https://ionicframework.com/docs/layout/grid) and came across the property "--ion-grid-columns" under the "Number of columns" section. Unfortunately, there was ...