问题描述:
在Angular 6中,使用HostListener装饰器的指令在生产版本中失效。以下是一个示例:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appCustomDirective]'
})
export class CustomDirective {
@HostListener('window:scroll', ['$event'])
onScroll(event) {
console.log('Scrolling...');
}
}
解决方法:
这个问题是由于Angular的AOT(Ahead-of-Time)编译器在生产版本中优化代码时,会删除未使用的装饰器代码导致的。
要解决这个问题,可以使用一个工具类来替代HostListener装饰器。以下是一个解决方法:
HostListenerUtil
的工具类,并在该类中实现所需的功能。例如,监听滚动事件并输出日志。import { Injectable } from '@angular/core';
@Injectable()
export class HostListenerUtil {
private scrollCallbacks: Function[] = [];
constructor() {
window.addEventListener('scroll', () => {
this.scrollCallbacks.forEach(callback => callback());
});
}
addScrollCallback(callback: Function) {
this.scrollCallbacks.push(callback);
}
}
HostListenerUtil
。import { Component, OnInit } from '@angular/core';
import { HostListenerUtil } from './host-listener.util';
@Component({
selector: 'app-custom-component',
template: 'Custom Component
'
})
export class CustomComponent implements OnInit {
constructor(private hostListenerUtil: HostListenerUtil) { }
ngOnInit() {
this.hostListenerUtil.addScrollCallback(() => {
console.log('Scrolling...');
});
}
}
HostListenerUtil
添加到providers
数组中。import { NgModule } from '@angular/core';
import { HostListenerUtil } from './host-listener.util';
import { CustomComponent } from './custom.component';
@NgModule({
declarations: [
CustomComponent
],
providers: [
HostListenerUtil
]
})
export class AppModule { }
现在,在生产版本中,您将能够监听滚动事件并输出日志。
这是一种解决方法,可以绕过HostListener装饰器在生产版本中失效的问题。