Angular 6 属性指令在引用时未定义

Angular 6 attribute directive undefined when referenced

我试图更好地理解自定义指令,因此我正在学习有关如何构建自定义属性指令的教程。但是,即使我很确定我已经完全按照教程进行操作,但是当我将指令设置为模板中的值时,它仍然返回为 undefined.

这是正在使用的模板:

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

这里是自定义指令的代码,它使鼠标悬停时的颜色变为绿色,而不是模板中指定的蓝色。

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

这是因为您可能没有名为 blue 的变量。你看,你正在使用 属性 绑定来调用你的指令要求值是一个组件 属性.

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:

在这里您可以阅读有关 property binding

的更多信息

对于您的示例,您有两种选择

  1. 您在名为 red 的组件中声明了一个变量并为其赋值;
  2. 当您使用 属性 绑定调用指令时,您可以简单地将值用作字符串,因此在您的情况下 [appHighlight]="'blue'" 也可以。
  3. 您不使用 属性 绑定,它会发出一个字符串形式的值 appHighlight="blue"