首页 > 解决方案 > onResize 事件在我的代码中不起作用,但在角度稍有变化时效果很好

问题描述

@HostListener('window:resize', ['$event'])
@HostBinding('class.blur') isBlur = false;

onResize(event?) {
  this.size = window.innerWidth - 50;
}

此代码可能会出现“ctx.isBlur 不是函数”之类的错误

@HostBinding('class.blur') isBlur = false;
@HostListener('window:resize', ['$event'])

onResize(event?) {
  this.size = window.innerWidth - 50;
}

这段代码运行良好......我不知道为什么......

正如我所料,isBlur = false; 在接收调整大小事件之前未定义。

标签: angularonresize

解决方案


因为@HostListener 需要一个函数来处理并且你给它一个属性。

您发布的两段代码也非常不同。

在下面的代码中,你装饰了 isBlur 的 setfunction 来设置元素的类

 @HostBinding('class.blur') 
 isBlur = false;

在幕后是这样的:

set isBlur(value:boolean) {
   this._isBlur = value;
   if(value){
        this.elementRef.nativeElement.classList.add(className);
   }
}

get isBlur() {
  return this._isBlur;
}

而方法装饰

@HostListener('window:resize', ['$event'])
onResize(event?) {
  this.size = window.innerWidth - 50;
}

是这样的:

decorate() {
  document.addEventListener(eventName, (event) => method(event);
}

推荐阅读