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;
}
}
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
red
and assign a value to it;[appHighlight]="'blue'"
will also work.appHighlight="blue"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With