What could be causing the ngStyle to malfunction?

I am facing an issue with my directive where the property color set in ngStyle is not being applied to the element. There are no errors shown by the compiler or console, and I have tried different syntaxes for ngStyle without success.

Below is the code from my app.modules file. Could there be an issue with module loading?

  import { Directive, ElementRef, OnInit, Renderer2, HostListener, Input } from '@angular/core';
            
            // custom directive which changes background color for odd and even values of index
            @Directive({
              selector: '[appChangecolor]'
            })
            export class ChangecolorDirective implements OnInit {
              @Input() index: any;
                       color: string;
            
              constructor(private elementRef: ElementRef, private render: Renderer2) { }
              // listnes to mouseenter event of the element on which custom directive is applied and calls the function
              @HostListener('mouseenter') bgColor() {
            
                if (this.index % 2 === 0) {
                  // style set through Renderer2 and not by directly accessing DOM element.
                  this.color = 'green';
                } else {
                  this.color = 'red';
                }
                  console.log(this.color);
              }
              // listens to the mouseleave event on the element on which directive is applied
              @HostListener('mouseleave') bgColorRm() {
                this.color = 'black';
                console.log(this.color);
              }
            
              ngOnInit() {
                this.index += 1;
              }
            }



        

Answer №1

Is a Directive really necessary for this task? Consider implementing it directly in the component:

onMouseEnter(index) {
  if (index % 2 === 0) {
    this.color = 'green';
   } else {
    this.color = 'red';
   }
}

onMouseLeave() {
   this.color = 'black';
}

Template

<tr *ngFor='let user of users; index as i' (mouseenter)="onMouseEnter(index)" (mouseleave)="onMouseLeave()" [ngStyle]="{'color': color}">
<td>{{i+1}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
</tr>

You can also explore using Renderer2 & ElementRef for more control:

this.render.setStyle(this.elementRef, 'color', this.color);

If utilizing ngStyle, you may need to implement EventEmitter. This is just a simple example to point you in the right direction...

@Output colorChanged: EventEmitter = new EventEmitter<string>();

@HostListener('mouseenter') bgColor() {
   ....
    this.colorChanged.emit(this.color);
   ....
}

@HostListener('mouseleave') bgColor() {
   ....
    this.colorChanged.emit(this.color);
   ....
}

<tr *ngFor='let user of users; index as i' appChangecolor [index]="i" [ngStyle]="{'color': color}" (colorChanged)="this.color=$event">

Answer №2

The CSS color property should not be directly applied to <tr> or <td> elements. To properly style the text within these elements, you can add a <p> tag inside each <td> and use the ngStyle directive on those <p> tags.

Here is an example:

<tr *ngFor='let user of users; index as i' appChangecolor [index]="i">
  <td><p [ngStyle]="{'color': color}">{{i+1}}</p></td>
  <td><p [ngStyle]="{'color': color}">{{user.firstName}}</p></td>
  <td><p [ngStyle]="{'color': color}">{{user.lastName}}</p></td>
  <td><p [ngStyle]="{'color': color}">{{user.email}}</p></td>
</tr>

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

The program encountered an error: Unable to access the 'toDate' property of an undefined value

Encountering an error in my Firebase project while running a Firebase function. The specific error message is: Cannot read property 'toDate' of undefined, related to converting admin.firestore.Timestamp to Date format. Any suggestions on how to ...

The binding for disabling Angular form controls is not functioning correctly

Upon page load, I have disabled a form control. The goal is to enable editing when a button is clicked by toggling the property that disabled the control. However, despite attempting to toggle this property, the control remains unchanged. Template <fo ...

Error with scoped slot typing in Vue3 using Vite and Typescript

I am currently working on a project using Vue3, Vite, and TypeScript as the devstack. I encountered an error related to v-slot that reads: Element implicitly has an 'any' type because expression of type '"default"' can't ...

Omitting ts/js files from the package with webpack

I am relatively new to webpack and currently working on an angular2 application with webpack. Our requirement includes having a settings file that should not be bundled, allowing the URL in the settings.js file to be changed after bundling. Here is the co ...

"Using the check function in JavaScript to determine if a value

I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list. Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object v ...

Discover how to transform a collection of numbers into a more expansive set that accurately reflects the original set

Consider an array with the following elements: [1,2,5,18,17,8]. Now, if you want to transform this array into a new one with a length of 40 while maintaining the same progression, you can use the following code: a = [1,2,5,18,17,8]; stepSize = 1 / (40 / ...

Tutorial on creating a subset of a series using jqplot

I am looking to display three series on the same canvas. The series are defined as follows: rec1 = [0, 0, 150, 200, 0 ]; rec2 = [60, 120, 179, 240, 300]; rec3 = [50, 100, 150, 200, 250]; Below are the source codes I am using to draw these series. $ ...

Looking to customize a jQuery modal window by having a Three.js canvas fill the entire width?

My concern revolves around the space occupied by a THREE.js canvas that I have inserted into a jQuery modal window. Initially, I created my code with the THREE.js canvas occupying the entire browser window without using any div elements. Here is a screens ...

AngularJS: Exploring the Connection with Array Elements

When working with AngularJS, I've noticed that I can easily bind text inputs to elements within arrays: <input type="text" ng-model="foo[2]" /> Is this a feature provided by AngularJS or simply happening by coincidence? However, when attempti ...

Is there a way to remove the row after hitting its corresponding button?

Having trouble working with table tags in a cshtml page, particularly when appending tr and td elements using ajax. I'm unsure of how to delete a row when it's clicked on and also how to retrieve the values of inputs within each row. /// <r ...

How can I set up unique values for a variable or constant in Angular 2 based on different environments?

Currently, I am working on a project that combines Angular 2/Ionic 2 with JEE 7. In this particular scenario: I have created an httpClient layer to handle all backend calls, and within this layer, there is a const variable called REST_BASE_PATH. During de ...

How can I retrieve response headers in my Angular4 component?

Hello folks, I'm encountering an issue with Angular4. I'm trying to return a response header to my component but it's not working as expected. Here is an example of my component code: this.filmService.create(this.film).subscribe( data =&g ...

Utilizing Vue JS to showcase a pop-up block when hovering over a specific image

There are four images displayed, and when you hover over each one, different content appears. For example, hovering over the first image reveals a green block, while hovering over the second image reveals a blue block. However, the current logic in place i ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

Using Typescript to create a mapped type that allows for making all properties read-only, with the exception of

I encountered a problem where I didn't want to repeatedly rewrite multiple interfaces. My requirement is to have one interface with full writing capabilities, while also having a duplicate of that interface where all fields are set as read-only excep ...

Getting the error message ""Cannot return null for non-nullable field" while trying to subscribe in NestJS using GraphQL"

I have developed a Node.js backend using Nestjs and incorporating Graphql, with my frontend built on Ionic/Angular utilizing Apollo-angular for graphql functionalities. However, I am encountering difficulties in subscribing to data additions or changes. St ...

AngularJS: Implementing bidirectional data binding between two separate controllers using a common service

I'm currently working on establishing a two-way data binding connection between two separate controllers and a shared service in AngularJS: app.factory("sharedScope", function($rootScope) { var scope = $rootScope.$new(true); scope.data = "ini ...

Encountering an Angular 12 error 401 upon refreshing the page

Currently, I am working on a login form using angular 12 with Spring Boot that includes basic authentication spring security. When a user successfully logs in, they are directed to the main page which offers CRUD actions as depicted in the images linked be ...

Generate HTML content based on the permissions from a REST API

I have a frontend that renders based on user permissions from a REST API. These permissions could include deleting users, creating users, adding users to workflows, and more. Most of these permissions are managed by an administrator. So my question is: H ...

Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route? This is a snippet from my app.routing.ts: // other route configurations... { path: 'scrapers/ ...