1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular 18 Directive - Change color of button on hover

Discussão em 'Angular' iniciado por Hina, Outubro 5, 2024.

  1. Hina

    Hina Guest

    I'm new to Angular, and I'm learning how to create a simple custom directive using Angular 18 that can change the background color of an element. I'm referring to the code provided in the Angular documentation here but it doesn't work. Is there anything I need to add to the code to make it work?

    Custom Directive:

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

    @Directive({
    selector: '[appHighlight]',
    standalone: true
    })
    export class HighlightDirective {

    constructor(private el: ElementRef, private render : Renderer2) {
    }

    @HostListener('mouseenter') OnMouseOver(eventData: Event){
    this.changeColor('yellow')
    }

    private changeColor(color :string)
    {
    this.render.setStyle(this.el.nativeElement,'backgroundcolor',color)
    }
    }


    Component :

    <div class="parent">
    <p appHighlight >Product Component</p>
    </div>


    Any solution thanks.

    I have tried to get solution using HostBinding but its not working. Expected: To understand how it works and what is the wrong in above code.

    Continue reading...

Compartilhe esta Página