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

标签 angular typescript angular-directive

我正在尝试更好地理解自定义指令,因此我正在关注如何构建自定义属性指令的教程。但是,即使我很确定我完全按照教程进行了操作,但当我将指令设置为模板中的一个值时,它仍然以 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 的变量。 .你看,你使用属性绑定(bind)来调用你的指令要求值是组件属性。

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. 当您使用属性绑定(bind)调用指令时,您可以简单地将值用作字符串,因此在您的情况下为 [appHighlight]="'blue'"也可以。
  3. 您不使用属性绑定(bind),它会以字符串的形式发出一个值 appHighlight="blue"

关于引用时未定义 Angular 6 属性指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446119/

相关文章:

javascript - 我无法使用 'disabled' 属性禁用 anchor

javascript - 如何使用 nz-radio-group 以 Angular 显示和隐藏其他项目

angular - .maps 和导入 'rxjs/add/operator/map' 出现问题;

javascript - 如何在 Angular 中使用 Jquery 查询生成器

javascript - AngularJS - 无法使用指令引用 ng-model 内的 $index

angular - 带有angular-cli的angular2中环境特定的服务端点

typescript - Observable 数组的 Observable 数组

reactjs - 在 React 中使用 TypeScript 输入动态标签?

angular - ngIf输入值

javascript - 在 AngularJS 中将 obj 从指令传递到 Controller