teumec
teumec

Reputation: 95

Angular activate @HostListener in ngAfterViewInit or ngOnInit

I have a component that is listening for the height and width of the component.

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.thewidth = event.target.innerWidth;
    this.theheight = event.target.innerHeight;
}

My issue is that I'm not getting any changes until the window is resized.

I need to make it do a check when the component is loaded too so I have the initial height and width.

How can I do this?

Upvotes: 0

Views: 1218

Answers (1)

Eddi
Eddi

Reputation: 821

You can obtain a reference to the host component by injecting ElementRef into the component:

constructor(private elementRef: ElementRef){}

ngAfterViewInit() {
    // timeout is needed when you are using `thewidth` or `theheight` inside your template
    setTimeout(() => {
        this.getHostDimensions();
    });
}

@HostListener('window:resize')
getHostDimensions() {
    const hostElement = this.elementRef.nativeElement;
    this.thewidth = hostElement.innerWidth;
    this.theheight = hostElement.innerHeight;
}

Upvotes: 1

Related Questions