Is it prohibited to use directive class styles in Angular?

I implemented a directive that, upon hovering over an element, adds an overlay to it. Each class in the dynamically added element has 5 to 8 properties, and I want to avoid using HostBinding or setStyle with Renderer2 on the element. Even after adding the classes in the component where the directive is applied, the class properties are not being applied.

** Issue: I don't want to use HostBinding or setStyle in the directive because I want to keep CSS and Typescript code separate. Also, I prefer not to add the directive classes in each component's .css file due to potential redundancy across multiple components where this hover effect should work. Ideally, I'd like to simply apply the directive like appHoverEdit to the element without having to add the CSS class in every component. Is there a way to include a styleURL property directly in the directive (similar to using host as seen in other posts)? **

I've successfully added the classes to the main styles.css file and they are working fine. However, I specifically want these classes to be applied only within the scope of that particular directive, not to the entire application. If you have a better solution or if I made any mistakes, please advise.

The directive implementation can be found below:

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

@Directive({
  selector: '[appHoverEdit]'
})
export class HoverEditDirective implements OnInit {
  edit = this.renderer.createElement('div');
  
  @HostListener('mouseenter') onMouseOver(event: Event){
    this.renderer.appendChild(this.element.nativeElement, this.edit);
  }
  @HostListener('mouseleave') onMouseLeave(event:Event){
    this.renderer.removeChild(this.element.nativeElement, this.edit, false);
  }

  constructor(private element: ElementRef,
    private renderer: Renderer2
  ) {}
    
  ngOnInit(){
    this.edit.innerHTML = `
      <div class="edit-schedule flex">
        <div class="h2">Edit</div>
        <div class="i-edit-container">
          <svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M22 36.6667H38.5M5.5 36.6667H8.57C9.46683 36.6667 9.91524 36.6667 10.3372 36.5654C10.7114 36.4755 11.069 36.3274 11.3971 36.1264C11.7671 35.8996 12.0842 35.5825 12.7184 34.9484L35.75 11.9167C37.2688 10.3979 37.2688 7.93546 35.75 6.41667C34.2313 4.89789 31.7688 4.89789 30.25 6.41667L7.21831 29.4484C6.58415 30.0825 6.26707 30.3996 6.04032 30.7696C5.83928 31.0977 5.69113 31.4554 5.60131 31.8295C5.5 32.2515 5.5 32.6999 5.5 33.5967V36.6667Z" stroke="black" stroke-width="3.66667" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
      </div>`;
  }
}

Answer №1

Indeed, there are two methods available for you to choose from.

  1. To style the DOM elements in edit, add a style tag dynamically!

CODE:

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

@Directive({
  selector: '[appHoverEdit]',
  standalone: true,
})
export class HoverEditDirective implements OnInit {
  edit = this.renderer.createElement('div');

  @HostListener('mouseenter') onmouseover(event: Event) {
    this.renderer.appendChild(this.element.nativeElement, this.edit);
  }
  @HostListener('mouseleave') onnmouseleave(event: Event) {
    this.renderer.removeChild(this.element.nativeElement, this.edit, false);
  }

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

  ngOnInit() {
    this.edit.innerHTML = `
      <style>
      .edit-schedule > .h2 {
        color: red !important;
      }
      .edit-schedule > .i-edit-container > svg {
        fill: red !important;
      }
      </style>
      <div class="edit-schedule flex">
        <div class="h2">Edit</div>
        <div class="i-edit-container">
          <svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M22 36.6667H38.5M5.5 36.6667H8.57C9.46683 36.6667 9.91524 36.6667 10.3372 36.5654C10.7114 36.4755 11.069 36.3274 11.3971 36.1264C11.7671 35.8996 12.0842 35.5825 12.7184 34.9484L35.75 11.9167C37.2688 10.3979 37.2688 7.93546 35.75 6.41667C34.2313 4.89789 31.7688 4.89789 30.25 6.41667L7.21831 29.4484C6.58415 30.0825 6.26707 30.3996 6.04032 30.7696C5.83928 31.0977 5.69113 31.4554 5.60131 31.8295C5.5 32.2515 5.5 32.6999 5.5 33.5967V36.6667Z" stroke="black" stroke-width="3.66667" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
      </div>`;
  }

}

Stackblitz Demo

  1. Alternatively, place the styles in global-styles.css and selectively apply them based on the parent class

global-styles.scss

.edit-schedule > .h2 {
  color: red !important;
}
.edit-schedule > .i-edit-container > svg {
  fill: red !important;
}

Stackblitz Demo

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

Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the ...

How can I remove a post from a list using AJAX?

Imagine I am creating a website that displays a feed of user posts, similar to Twitter's timeline. If a user wants to delete a post from the feed, I have set up a dynamic list using PHP and MySQL database. Additionally, I have a delete.php file which ...

What is the process behind the creation of the class or id fields in HTML for Gmail and Quora? How are these

When using Gmail: <tr class="zA yO" id=":1t4"> While on Quora: <span id="ld_zpQ1Cb_27965"> What is the purpose behind this and what specific tool do they employ to achieve it? ...

I am having trouble using a form to filter by year in Angular

Here's an example link to view: https://stackblitz.com/edit/angular-ivy-byvfjy?file=src/app/ofertas/filtro-ofertas/filtro-ofertas.component.ts I have a requirement to filter the table by year. https://i.sstatic.net/Bfu7b.jpg However, I keep encount ...

Give a CSS Element a specific class

Can all h3 elements be styled with the class responsive-heading using only CSS? Take a look at the CSS snippet provided for more clarity: h3 { .responsive-heading } /* The responsive-heading class is defined in another CSS file and includes: .respons ...

What is the method for emphasizing links in the navigation bar with Bootstrap 3?

I am currently working on applying custom CSS styles to the Bootstrap navbar in order to have the link text underlined when hovered over, with a fade-in effect as well. To see what I have accomplished so far, you can view it here: https://jsfiddle.net/xfd ...

Angular 6 - implementing a dynamic carousel with bootstrap styling

I am currently working on a carousel using bootstrap4 where the images are sourced from an array. However, I am facing an issue where the first element must have the active class. <div id="carouselExampleFade" class="carousel slide carousel-fade" dat ...

Techniques for determining if a file is empty using jQuery

Just starting out with JS. I want to validate the file input element before form submission using jQuery/JavaScript. I've researched various solutions, but nothing seems to be working for me. I'm trying to avoid displaying "/c/fakepath" as the ...

Safari causing margin problems

Encountering a margin problem specifically with Safari that I'm having trouble debugging. While everything functions properly in Firefox, Chrome, IE, etc., Safari presents issues. My content div is positioned just below the header, but in Safari, it o ...

Tricks for prompting Angular2 to recreate components every time they are displayed

Within our angular2 Typescript application, the functionality of our components is heavily reliant on the parameters they receive from the router, resulting in dynamic behavior based on these inputs. The current stage of development for the application is ...

Display information upon the clicking of a button and update the color of the selected button

When a button is pressed, I want to display content and change the color of the active button. Currently, I can do each operation individually, but I'm struggling to merge these functionalities. This is how my script looks like for displaying the con ...

Reorganize elements within a twig form to suit your preferences - Symfony 3

I have a form displayed on my page that I need to style according to a provided mock-up for mobile devices. Here is the mock-up I am supposed to follow: https://i.sstatic.net/ojxWb.png This is how the layout currently looks on my page: https://i.sstati ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

Positioning elements using CSS Flexbox within the body of a modal dialog box

Hey there! I'm trying to achieve a specific style using flexbox, but I'm having trouble with placing the modal close button on top of the image. If anyone has any tips or guidance, I would greatly appreciate it! Here's what I have so far: ht ...

What causes the image to remain unchanged while the rest of the divs update when navigating with the previous, next, or random buttons?

Whenever I interact with the navigation buttons - specifically previous, next, and random - the contents of all div elements change accordingly. The image element, however, remains unchanged. I am encountering an issue where the image does not correspond t ...

Creating a custom arrow design for a select input field using CSS

I'm currently developing a website (using Wordpress with a custom theme) and I want to incorporate an up/down arrow in the select input field using CSS. The HTML code I have for creating the up/down arrow in the select input field is as follows: < ...

Encountered a TypeError in Angular printjs: Object(...) function not recognized

I'm currently working on integrating the printJS library into an Angular project to print an image in PNG format. To begin, I added the following import statement: import { printJS } from "print-js/dist/print.min.js"; Next, I implemented the pri ...

What is the best way to create an HTML template with a table where the first column is divided into four cells and the second column only has one

Currently, I am working on a template using HTML and CSS. One issue that I am facing involves designing a table template with HTML and CSS. The specific problem occurs in the second row of the table where there are 4 cells in the first column and only one ...

Unable to apply styling to border when clicking on radio button in React

I've created these divs to act like radio buttons: [![these 4divs][1]][1] When I click on one of them, I want the border to turn blue like this: border: 2px solid blue; However, instead, the issue shown below is happening: [![the problem][2]][2] ...

Tips for positioning a container at the center of the screen

I am having trouble centering text in the middle of my screen. Despite my efforts, it seems like it's not working as expected. Would someone be able to review the following index.html code and point out where I might be going wrong? <!DOCTYPE html& ...