指令不适用于不同的文件

时间:2017-11-08 09:08:59

标签: angular typescript angular2-directives

我目前遇到@Directive@Hostlistener的问题,我很乐意帮助

我不知道为什么当我将指令添加到输入时它没有做任何事情,它不会触发任何事件,甚至不是console.log()和我&#39我现在绝望了,因为必定会有一些我失踪的东西,但我现在不知道。

我有以下项目结构。

app
|
|___ components
|   |
|   |___ Autocomplete
|       |___ autcomplete.component.html
|       |___ autcomplete.component.ts
|       |___ autcomplete.component.css
|
|
|___ directives
|   |___ keyboard.directive.ts
|
|___ app.module.ts

autocomplete.component.html

<div class="input-field">
    <label [attr.for]="id">{{ label }}</label>
    <input keyboard type="text" [(ngModel)]="inputData" 
           name="inputData" [attr.id]="id"
           class="autocomplete-input" autocomplete="off"/>
</div>

keyboard.directive.ts

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

@Directive({
selector: '[keyboard]'
})

export class KeyboardDirective {

    constructor(el: ElementRef) {}

    @HostListener('focus', ['$event']) onFocus(value: string) {
        console.log('Focus caught.');
    }

    @HostListener('keydown', ['$event']) onKeyPressed(e: any) {
        console.log('keydown event);
    }
}

我的app.module.ts看起来像这样:

import {KeyboardDirective} from '../app/directives/keyboard.directive';

@NgModule({
    declarations: [
        KeyboardDirective
    ],
    providers: [],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ],
    bootstrap: [AppComponent]
})

export class AppModule {}

我尝试将它添加到组件本身并且它可以正常工作,但是当它在其他文件夹中时它没有,所以我要感谢有关为什么会发生这种情况的任何提示。

1 个答案:

答案 0 :(得分:0)

由于我没有完整的代码,我会列出您可能出现的错误:

1 - 在声明自动填充组件的模块中,您应该导入该指令。我没有看到你的组件在任何地方被宣布。

2 - 如果指令不在同一模块中,则需要导入声明指令的模块。由于您在appModule中声明了它,我建议您为指令创建另一个模块。

3 - 在指令模块中,您需要导出指令。否则,您将收到错误消息,指出指令/组件未知。

如果您可以尝试并更新您的帖子,那就太好了!