Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 attribute directive undefined when referenced

I am trying to understand custom directives better and so I am following a tutorial on how to build a custom attribute directive. However, even though I am pretty sure I have followed the tutorial exactly, when I set my directive to a value in the template, it is still coming back as undefined.

Here is the template being used:

<div [appHighlight]='blue'>
 TESTING TESTING TESTING
</div>

And here is the code for the custom directive, which is making the color green on mouseover instead of blue, which is specified in the template.

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

@Directive({
  selector: '[appHighlight]'
})
export class ColorDirective {
  @Input('appHighlight') hightlightColor: string;

  element: ElementRef;
  constructor(private el: ElementRef) {
   }

   @HostListener('mouseenter') onMouseEneter() {
     console.log(this.hightlightColor); //coming back as undefined
     this.hightlight(this.hightlightColor || 'green');
   }

   @HostListener('mouseleave') onmouseleave() {
     this.hightlight(null);
   }

   private hightlight( color: string) {
     this.el.nativeElement.style.color = color;
   }
}
like image 281
phelhe Avatar asked Oct 18 '25 23:10

phelhe


1 Answers

This is due to the fact that you probably don't have a variable named blue. You see, you're using property binding to call your directive requires the value to be a components property.

Write a template property binding to set a property of a view element. The binding sets the property to the value of a template expression.

The most common property binding sets an element property to a component property value. An example is binding the src property of an image element to a component's heroImageUrl property:

Here's where you can read more about property binding

For your example to your you have a couple of options

  1. You declare a variable in your component named red and assign a value to it;
  2. When you're calling your directive with property binding, you can simply use the value as a string, so in your case [appHighlight]="'blue'" will also work.
  3. You don't use property binding, and it will emit a value as a string appHighlight="blue"
like image 194
k.s. Avatar answered Oct 20 '25 13:10

k.s.