How to utilize the CSS hover feature within an Angular directive?

Presented here is the default directive.

import { Directive, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: '[newBox]'
})
export class BoxDirective {

  @Input() backgroundColor = '#fff';
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit(): void {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', this.backgroundColor);
  }

}

I am now looking to dynamically change the background color on hover using this directive. How can I achieve this?

Answer №1

Implement HostListener for event monitoring


  @HostListener('mouseover')
  onMouseOver() {
    this.backgroundStyle = '#fff';
  }

  @HostListener('mouseout')
  onMouseOut() {
    this.backgroundStyle = '#000';
  }

Answer №2

import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appHover]'
})
export class HoverDirective implements OnInit {
  @HostListener('mouseenter') onMouseEnter(){
    this.renderer2.setStyle(this.elRef.nativeElement,'fontSize','100px')
    this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
    this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
  }
@Input('appHover') style:string='';
  @HostListener('mouseout') onMouseOut(){
    this.renderer2.setStyle(this.elRef.nativeElement,'fontSize',this.style)
    this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
    this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
  }

  constructor(private elRef:ElementRef,private renderer2:Renderer2) { }
  ngOnInit(): void {
  
  }
  
}


proceed to app.component.html


then apply the directive.

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

Internet Explorer is failing to render SVG as content within a pseudo element such as :before or :after

Looking to tackle an issue that stems from the following discussion: Is there a way to use SVG as content in a pseudo element :before or :after. I'm attempting to add a svg triangle after a div using a pseudo-class. div{ background-color: black; w ...

Is it possible to switch between mat-checkbox and mat-radio-button within an Angular reactive form?

As I develop a quiz application, I face the challenge of dynamically switching between mat-checkbox and mat-radio-button based on the number of answers for each question. For instance, Question #1 is a single choice question and utilizes mat-radio-button, ...

Modify CSS using Javascript by targeting the class of ".modalDialog > div {}"

I am currently working on a project that involves creating a Modal Layer using CSS. I have successfully implemented the modal layer, but now I need to figure out how to change the width from the default 400px to something else when I open it with Javascrip ...

Angular web application can retrieve JSON data from a web API controller, allowing for

I'm currently utilizing ASP.NET Core on the backend and Angular on the frontend. My API delivers data in JSON format from the backend. I've set up a service to fetch the API data, but it's returning 'undefined' at the moment. emp ...

CSS - stacking containers vertically with scrollbars

I am in need of a vertical stack of blocks, which may include scrolls, contained within a fixed-sized container without scrolls. The number of visible blocks is dynamically managed by JavaScript code. Some blocks can be hidden or shown, and when a block is ...

How can I use CSS to transform a "+" symbol to an "x"?

When I created an accordion using HTML, JS, and CSS, I encountered a problem. The "+" sign in the accordion does not rotate correctly as it should. Instead of rotating from the middle of the "+" sign, it rotates from the top. This is my HTML code: <di ...

Ways to Export HTML to Document without any borders or colorful text

How can I make a contentEditable area visible when filling text and then disappear when exporting the document? I found a script online that allows you to do this, but the issue is that the contentEditable area is not visible until clicked on. To address t ...

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

Blending HTML template and WordPress PHP file

I am facing a challenge while attempting to implement a Wordpress template on one of the pages of my website, specifically at http://www.windowblindshadeshutters.com/blog/. The blog has been successfully created, however, I am having trouble preserving our ...

I am experiencing an issue where notifications are not appearing on my Ionic 3 device

I implemented the notification feature on my device using cordova plugin add cordova-plugin-fcm. I am working with Ionic 3. I am currently facing a roadblock and could use some assistance to resolve this issue. app.componet.ts import { Component } from ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

Challenges arise with CSS alignment when adding d3.js charts to a webpage

I'm puzzled by the empty space that appears between the left column (highlighted in the image) and the header. This peculiar gap only seems to occur when the middle column is filled with a chart. I've scrutinized the code using Chrome Developer t ...

What are the best ways to utilize dynamic CSS on a smartphone browser for optimal performance?

Struggling to optimize my web application for mobile devices, I've encountered challenges with consistent display across different browsers. My idea is to utilize device capability detection to adjust widths and font sizes dynamically based on screen ...

Ways to prevent the use of the JavaScript increment (++) or decrement (--)

I have created two functions for a multi-step configuration on a webpage. protected clickNext(event:any, config:any) : any{ this.activeIndex++; } protected clickPrev(event:any, config:any) : any{ this.activeIndex--; } Here are the buttons: < ...

Build an Angular wrapper component for the phone textbox functionality

Looking to transform the Phone Mask solution below into an Angular component. Does anyone have a method to accomplish this? * Any solution that results in a similar component for a Phone textbox will suffice. Mask for an Input to allow phone numbers? ht ...

Rearranging data received from an Observable

TL;DR I am working on an Angular app where I need to shuffle an array of names retrieved from a network request and ensure that each group of 6 names selected is unique. However, I noticed duplicates in the selections. Here's a CodePen example using o ...

Content overflowing beyond the boundaries of the parent DIV in Internet Explorer 6

Take a look at the code snippet below: <div style="width: 50px; border: 1px solid green;"> <div style="position: absolute;"> add whatever text you'd like </div> </div> The display in modern browsers (such as I ...

If the SASS condition matches the variable for the background color, then

I attempted to create a conditional statement in my component using Sass @if and @else. The condition I set was that if background == var(--bg-danger), the color should be white. However, it only returned white and did not trigger the else condition. @mixi ...

Experiencing issues with the redirect button on the navigation bar of my website

Video: https://youtu.be/aOtayR8LOuc It is essential that when I click a button on my navigation bar, it will navigate to the correct page. However, since the same nav bar is present on each page, it sometimes tries to redirect to the current page multiple ...

Problem with input field borders in Firefox when displayed within table cells

Demo When clicking on any cell in the table within the JSFiddle using Firefox, you may notice that the bottom and right borders are hidden. Is there a clever solution to overcome this issue? I have experimented with a few approaches but none of them work ...