For individuals looking to obtain the height and width of their device even when the display is adjusted (dynamically & in real-time):
In the specified Component, include:
import { HostListener } from "@angular/core";
Within the component's class body, add the following:
@HostListener('window:resize', ['$event'])
onResize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
}
Within the component's constructor
, invoke the onResize
method to initialize the variables. Ensure they are declared first as well.
constructor() {
this.onResize();
}
Complete code:
import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class FooComponent implements OnInit {
screenHeight: number;
screenWidth: number;
constructor() {
this.getScreenSize();
}
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
console.log(this.screenHeight, this.screenWidth);
}
}