javascript - 自定义指令输入返回错误 Angular 5

标签 javascript angular typescript

我有这样设置的自定义指令..

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

@Directive({
    selector: '[pieceRate]'
})
export class PieceRateDirective {
    @HostListener('input', ['$event'])
    @Input() dollarMax: string;
    @Input() centMax: string;
    onkeydown(event: KeyboardEvent) {
      const input = event.target as HTMLInputElement;
      console.log(this.dollarMax);
      console.log(this.centMax);
  }
}

我将它导入到一个共享模块中,该共享模块被导入到我的主模块中,所以..

共享模块

import { PieceRateDirective} from '@app/directives...'
...

@NgModule({
   imports..
   declarations: [
     PieceRateDirective
   ],
   exports: [
      PieceRateDirective
   ]
})

主模块

import { SharedModule } from '@app/shared.module';
...

@NgModule({
   imports: [
      SharedModule
   ]
})
...

所以一切看起来都很好,但是当我真正尝试像这样使用我的指令时......

<input
   pieceRate
   [dollarMax]="rangeTo?.toString().split('.')[0]"
   [(ngModel)]="dollarPieceRate"
   type="number" >

然后输入一个数字我得到这个错误

类型错误:jit_nodeValue_10(...).dollarMax 不是函数

我不确定是什么导致了这个问题..

如有任何帮助,我们将不胜感激!

最佳答案

@HostListener装饰器用于将处理程序关联到事件。在本例中,onkeydown 的声明应该紧跟装饰器:

export class PieceRateDirective {

  @Input() dollarMax: string;
  @Input() centMax: string;

  @HostListener('input', ['$event'])
  onkeydown(event: KeyboardEvent) {
    ...
  }
}

关于javascript - 自定义指令输入返回错误 Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826144/

相关文章:

javascript - 在 React Native 中获取 TextInput 值和复选框状态

angular - 将 CanActivate() 委托(delegate)给组件

javascript - 如何在Angular2中调用Polymer元素方法?

javascript - 我可以获得从 Firestore 集合组查询中获取的文档的路径或引用吗?

javascript - 创建一个自定义 Angular 原理图来生成以下划线开头的文件?

css - 使用 ngStyle 定义网格区域时遇到问题

javascript - 类型错误 : undefined is not an object (evaluating 'item.phoneNumbers[0]' )

javascript - `alert` 更改变量值时出错

javascript - 添加事件类以在单击和手动滚动时平滑页面滚动

对于使用 cli 生成的新组件,Angular 语言服务在 vs 代码中不起作用