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

The act of securing a host connection and actively monitoring it for

Wondering how to incorporate host listeners and host bindings in Angular 2? In my attempts to use a host listener, I encountered an error message indicating "Declaration Expected". Here's what I tried: In the app.component.ts file: import {Componen ...

What is the best method for confirming that a string is not undefined, null, or an empty string in an Angular template?

Is there an efficient method to verify whether a string is not undefined, null, or '' in an angular template? If the value is valid, then show this section. <div class="flex-row date-area" *ngIf="startDate !== undefined && startDate ...

The table is not properly displaying within the parent scrolled div due to issues with the fixed positioning

Apologies for any language barrier. I am encountering an issue with a PHP page that includes a table meant to be displayed as position:fixed; however, it consistently appears above the scrollbars and does not stay within the parent div. View screenshot he ...

Creating stunning visuals with the power of SVG

I need to create a graphics editor similar to Paint using SVG for a school project. I have JavaScript code for drawing shapes like circles and lines, but when I try to add them to an onClick function for a button, it doesn't seem to be working. funct ...

A newline within the source code that does not display as a space when rendered

Written in Chinese, I have a lengthy paragraph that lacks spaces as the language's punctuation automatically creates spacing. The issue arises when inputting this paragraph into VSCode - there's no seamless way to incorporate line breaks in the s ...

What could be the reason behind my Ionic app receiving a 401 error from an API call while Postman is not encountering the

Following the instructions from a tutorial on Smart of the Home, I implemented the code below in a provider for my Ionic 2 App. return new Promise(resolve => { // Using Angular HTTP provider to make a request and process the response let headers = ...

Angular 4 Query Building Plugin

Looking for a query builder plugin compatible with Angular 4 to create nested queries in my project. Some options I found include: https://www.npmjs.com/package/angular2-query-builder (Requires Angular 4+ ) (For AngularJS) (For Angular JS). The c ...

Issues arise with the functionalities of FireFox related to transformations and transitions

I've been working on my CSS and here is what I have: img.buttonImg { -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; -ms-transition: all 0.5s ease-in-out; transition: ...

Ways to subtly adjust the edges of text in a design

https://i.stack.imgur.com/sr4PF.pngIs there a way to adjust the border of text that already has a border applied? I have successfully created the text with the border using the following CSS: h1 { font-size: 35pt; text-align: center; font-family: ...

What is the best way to ensure that the child element of a Material UI TableCell Component occupies the full height of the cell?

I am currently using MUI version 5 to create a table. In this table, there are two columns with cells that contain multiline TextFields. My goal is to have the TextFields completely fill the cell area. However, I am encountering an issue where when I start ...

Enhance your webpage's body by zooming in using jQuery on Mozilla Firefox

I have a webpage and I would like to zoom its body when it loads using jQuery. However, the CSS zoom feature is not working in Mozilla Firefox. This is what I currently am using: $("body").css("zoom", "1.05"); It worked in Chrome, Opera, and Edge, but un ...

Tips for creating dynamic row styles in a fluid table layout?

Could someone help me figure this out? I'm not familiar with JavaScript and need assistance as I've never created it, only edited existing scripts. I have a layout with two tables side-by-side. On mobile devices, the second table is pushed below ...

detecting syntax errors in CSS with @media queries and keyframes

/*general CSS setting for all device types above hd*/ * { margin: 0; padding: 0; } #watchonly { display: none; } ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

Sleek and versatile sidebar reaching full height

Is there a way to make my sidebar cover the full height of the screen without using position: fixed? The code I've tried doesn't seem quite right. Any tips? JSFindle: http://jsfiddle.net/Pw4FN/57/ if($(window).height() > $('#page-contai ...

Centering the header image on the screen creates a visually appealing focal point

Looking to design a header image for my website that always stays centered. I want the image to stand out and remain in the middle even when the browser window is resized. I found an example on this website that achieves this effortlessly. ...

Maintain the border styling of a radio button when it is in the selected state

Having an issue with the radio type options - when selected, a blue border appears but disappears if clicking elsewhere. Need the blue border effect to stay even when clicked outside, unless switching to the other option. Looking to align the price in th ...

Angular - optional parameter in route using ngRouter

I have a question regarding using Angular (4) with the @angular/router. I want to be able to include optional parameters in a path style, but am facing some challenges. Currently, my code looks like this: { path: 'cars', component: CarComponent ...

Converting a string to a number in an Angular template

Within my select box, I am capturing the selected value and binding it to the variable startingYear. However, I need the type of startingYear to be a number, but it is currently registering as a string. Is there a way to convert it to a number? console ...