【问题标题】:Directive throw error, not able to understand指令抛出错误,看不懂
【发布时间】:2018-02-02 10:45:39
【问题描述】:

我使用 angular5,在应用程序中我创建了一个引发错误的指令。我根本无法理解这个问题,任何人都可以在这里帮助我吗?

代码:

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

@Directive({
    selector: '[zoom]'
})
export class ZoomDirective {

    constructor(private el:ElementRef, private renderer:Renderer) { 

        @HostListener('mouseenter') onMouseEnter() {
            this.highlight('yellow');
        }

    }

}

错误:

cannot find onMouseEnter, did you mean onmouseenter

我在onMouseEnterthis.highlight('yellow'); 得到突出显示,这是什么问题?

角度 cli 详细信息:

Angular CLI: 1.6.5
Node: 6.11.4
OS: win32 x64
Angular: 5.2.3

【问题讨论】:

  • cannot find onMouseEnter, did you mean onmouseenter 它实际上是在告诉您使用onmouseenter 而不是onMouseEnter。可以试试吗?
  • 不,我试过得到同样的错误,angular.io/guide/attribute-directives
  • @HostListener('mouseenter') 应该在构造函数之外声明。
  • 但是在this.highlight('yellow'); 出现错误你能更新我的代码作为答案吗?

标签: angular angular5


【解决方案1】:

@HostListener('mouseenter') 应该在构造函数之外声明:

export class ZoomDirective {

    constructor(private el:ElementRef, private renderer:Renderer) { }

    @HostListener('mouseenter') onMouseEnter() {
        this.highlight('yellow');
    }

    private highlight(color: string) {
        this.el.nativeElement.style.backgroundColor = color;
    }
}

更多示例请参见Angular documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2013-12-15
    • 2012-11-21
    • 2017-08-21
    • 1970-01-01
    • 2015-04-28
    • 2017-11-20
    相关资源
    最近更新 更多