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>`;
}
}