3

i am a newbie to programming. I have tried this code but @hostlistner part is not working i have used bootstrap version 4

it doesn't give any compile error also

 element.nativeElement.style.color = 'red' 

this statement is working but

 this.element.nativeElement.style.color = 'blue';

this one doesn't

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

         @Directive({
          selector: '[setmycolor]'
           })
          export class SetmycolorDirective {

          constructor(private element:ElementRef) {
          element.nativeElement.style.color = 'red';
          }


          @HostListener('onmouseenter')onMouseEnter(){
          this.element.nativeElement.style.color = 'blue';
          }

          }

the code in app

  • 1
    The name of the event is `mouseenter`, not `onmouseenter`. – JB Nizet May 01 '19 at 14:05
  • 1
    addind an event listener in javascript is object.addEventListener("mouseenter", myScript). Then as @JBNizet said , is mouseenter – CREM May 01 '19 at 14:09
  • 1
    this may help: https://stackoverflow.com/questions/51491225/how-to-use-mouseover-and-mouseout-in-angular-6 – Hasnain Ali Sohrani May 01 '19 at 14:13
  • 1
    I understand this may be an academic / learning exercise for the mouse events or hostlisteners in angular, but the way I'd usually handle this is with the css :hover selector which is much simpler and performs better. – bryan60 May 01 '19 at 14:47

2 Answers2

2

Try below :

The name of the listening event is mouseenter, not onmouseenter. Hopefully you got it.:)

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

         @Directive({
          selector: '[setmycolor]'
           })
          export class SetmycolorDirective {

          constructor(private element:ElementRef) {
          element.nativeElement.style.color = 'red';
          }


          @HostListener('mouseenter') onMouseEnter(){ //SEE HERE
          this.element.nativeElement.style.color = 'blue';
          }

          }
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21
1

Your code is correct, just replace onmouseenter with mouseenter

@HostListener('mouseenter') onMouseEnter(){
          this.element.nativeElement.style.color = 'blue';
          }
Abhishek Gautam
  • 1,617
  • 3
  • 18
  • 29