Challenges encountered when setting a value to a custom directive via property binding

I'm working on a question.component.html template where I render different options for a specific question. The goal is to change the background color of an option to yellow if the user selects the correct answer, and to red if they choose incorrectly.

Here is the code snippet:

question.component.html

`<div class="options">
    <ol *ngFor="let option of optionsList; let i = index">
        <li (click)="optionChose(i)">
            <div appChangeBg 
                [isCorrect] = "isCorrectOptionChosen" 
                 class="card">
                 {{ option }}
            </div>
        </li>
    </ol>
</div>`

question.component.ts

`export class QuestionComponent implements OnInit {
   isCorrectOptionChosen: boolean;
     optionChose(index: number) {
        if (index === this.correctOptionIndex) {
            this.isCorrectOptionChosen = true;
        } else {
           this.isCorrectOptionChosen = false;
        }
     }
 }`

change-bg.directive.ts

`@Directive({
    selector: '[appChangeBg]'
 })
 export class ChangeBgDirective {
    @Input() isCorrect: boolean = false;

    constructor(private elRef: ElementRef, private renderer: Renderer2) {}

    @HostListener('click') answer() {
      if (this.isCorrect === true) {
         this.renderer.setStyle(this.elRef.nativeElement, 'background-color', 'yellow');
    }else{
       this.renderer.setStyle(this.elRef.nativeElement, 'background-color', 'red');
    }
  }
}  

However, I am facing an issue where the isCorrect variable in the directive is undefined initially. This results in the incorrect color being displayed even when the correct option is chosen. I need help troubleshooting this problem and finding a solution for it.

Answer №1

It seems that the issue lies in the sequence of events when the click event triggers the optionChose method, and assigns a value to the isCorrectOptionChosen variable before the "click" event is fired for the ChangeBgDirective.

To resolve this, instead of assigning the value from the optionChose method only upon click, you can predefine the value in the HTML template rendering process.

Please be aware that invoking methods directly within the HTML template could potentially impact performance. To address this concern, consider implementing a Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'correctOption',
})
export class CorrectOptionPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    let correctOptionIndex = args;

    return value === correctOptionIndex;
  }
}

Ensure to register the CorrectOptionPipe in the AppModule.

Subsequently, remove the (click)="optionChose(i)" attribute from the HTML element, and utilize the CorrectOptionPipe:

<ol *ngFor="let option of optionsList; let i = index">
    <li>
        <div appChangeBg 
            [isCorrect]="i | correctOption: correctOptionIndex" 
             class="card">
             {{ option }}
        </div>
    </li>
</ol>

Check out the Demo on StackBlitz

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

Issue: The 'async' pipe was not found after updating to AOT and IVY

I recently upgraded my project to AOT compliance and ever since, I've been experiencing issues with the | async pipe in my HTML code. Here is an example of what my HTML looks like: <div *ngIf="(mySubscription$| async) != null"> //some ...

The Angular compiler encounters an error when working with jsonwebtoken

Having some trouble with adding jsonwebtoken to my code. VS Code seems to think the code is fine, but the compiler keeps failing Any ideas on why this might be happening? Thanks for any help! Here's a snippet of my code: this.http .po ...

Angular 2 code test coverage

Looking to calculate the code coverage of my Angular 2 code. Wondering if there are any plugins available for VS Code or WebStorm that can assist with this. My unit testing is done using Jasmine and Karma. ...

Decipher the splitButton tag from PrimeNG

I am currently attempting to translate items from "p-splitButton", but I am facing a challenge because the "items" is an object. How can I accomplish this task? [model]="items | translate" app.component.html <p-splitButton label="Save" icon="pi pi- ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

Angular2: Observable flatMap issue with Undefined Property Subscribe

I am using the final version of Angular 2 and attempting to make an HTTP request that relies on another HTTP request. In my scenario, I am trying to retrieve an account with the user ID as a parameter which is obtained from another HTTP request (getUser). ...

Angular developers may encounter a dependency conflict while attempting to install ngx-cookie

I'm currently facing an issue while attempting to add the ngx-cookie package for utilizing the CookieService in my application. Unfortunately, I am encountering some dependency conflicts that look like the following: $ npm install ngx-cookie --save np ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Exploring Angular: A Guide to Importing Material Components

Trying to incorporate elements such as sliders and tooltips into my project, but encountering issues with imports. I've experimented with adding the import statement for MatSliderModule in various locations like app.module.ts and specific component mo ...

Encountering a CORS issue when utilizing passport-facebook for Facebook authentication in my MEAN application

I'm currently working on implementing a Facebook login feature for my web app, built with express js, mongodb, and angular 2. The client-side of the app is generated using angular-cli (running on port 4200), and I'm utilizing the proxy config pr ...

The value calculated by Auto does not display as a valid number in Angular 8 until it has been manually edited

Having an issue with a form submission for invoicing. The total value field, which is auto-calculated based on quantity and unit price, does not show up as numeric data in the backend onSubmit event unless I manually interact with it by adding something ...

Tips for resolving the issue: "Encountered error loading module script..." in Angular 8 and Electron 5

I have been working on developing an Electron 5 app using Angular 8. Despite following numerous online tutorials, I keep encountering the same error. Initially, I set up a new project and ran ng serve --open, which successfully displayed the default angul ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Challenges with image cropping in Angular causing performance problems

Utilizing this specific component for image cropping within an ionic/angular8 project has been causing severe performance issues, leading to unresponsiveness on mobile devices. Interestingly, the desktop version does not encounter any problems and the crop ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

Unveiling RxJs: The secret to extracting the notifier value using the takeuntil operator

I have a straightforward Rxjs timer set up that runs until a notifier emits a signal, it's pretty basic so far. enum TimerResult = { COMPLETE, ABORTED, SKIPPED }; _notifier: Subject<TimerResult> = new Subject(); notifier$: Observab ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Printing content from an Angular dashboard can be achieved by following a few

Currently, I am working on developing a legal document automation program for my company. However, I have encountered an issue during the final stages of completing this web application. For the layout and setup, I am using the default angular Dashboard l ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...