onResize event did not work in my code but works well with a small change in angular

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

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

this code can occur error like "ctx.isBlur is not a function"

but

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

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

this code works well... I don't know why...

As I expect , isBlur = false; is not defined before receive resize event.

1

There are 1 answers

3
misha130 On BEST ANSWER

Because @HostListener expects a function to handle and you give it a property.

Also the two pieces of code you posted are very different.

In the following piece of code you decorate the setfunction of the isBlur to also set the class of the element

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

Behind the scenes its something like this:

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

get isBlur() {
  return this._isBlur;
}

While the method decoration

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

is something like:

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