指令在不同的文件中不起作用

Directive doesn't work within different files

我目前遇到 @Directives 和 @Hostlisteners 的问题,我希望得到你的帮助

我不知道为什么当我将指令添加到输入时它没有做任何事情,它没有触发任何事件,甚至没有 console.log() 我现在很绝望,因为一定有什么东西是我遗漏的,但我现在不知道是什么。

我有以下项目结构。

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 - 在您声明自动完成组件的模块中,您应该导入该指令。我没有看到您的组件在任何地方被声明。

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

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

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