Angular 如何使用HostListener
我想知道如何使用Angular 如何使用HostListener,angular,Angular,我想知道如何使用@HostListener。我找到的唯一信息是: 我正在尝试记录用户单击的元素。我试过这样做: @HostListener('click')({ onClick(e) { console.log(e) } }) 但随后我收到一个错误: TypeError: decorator is not a function(…) 有什么想法吗?错误信息非常准确。decorator仅用于修饰函数(或类、字段、参数等),只需将其置于要修饰的代码之前: @Hos
@HostListener
。我找到的唯一信息是:
我正在尝试记录用户单击的元素。我试过这样做:
@HostListener('click')({
onClick(e) {
console.log(e)
}
})
但随后我收到一个错误:
TypeError: decorator is not a function(…)
有什么想法吗?错误信息非常准确。decorator仅用于修饰函数(或类、字段、参数等),只需将其置于要修饰的代码之前:
@HostListener('click',['$event']))
onClick(e){
控制台日志(e)
}
谢谢!我的问题还在于我把它放在了课堂之外。关于为什么“e”可能是未定义的,有什么想法吗?类的“外部”替代方法是将它添加到@Component()
(或@Directive()
装饰器,如@Component({…,host:{'(click):'onClick($event)})
,它与我的答案中的代码相同。如果onClick(e),实际上没有
被调用时,e
应该有一个值。你能试试['$event.target']
是否有什么不同吗?当我添加$event.target时,它会正常工作。有趣的是,@Component()
装饰器中的变量有$event
(没有.target
)?它也可以工作,但它只提供不同的输出。然后它不传递我选中的div,而是传递document.addEventListener的结果
TypeError: decorator is not a function(…)