In this section, we are going to learn about getting the height and width of the screen. We will use Angular to do this. If we don’t have knowledge about screen height, we can use the below examples because these examples give detailed knowledge about the height and weight of the screen. In our below application, we are going to implement a get screen width and height. In order to get the height and width of the window, we can use various versions of Angular applications such as Angular 6, 7, 8, 9, 10, and 11.
In our Angular application, we will get the size of a window on resize events. Here, we will explain two examples to get window size. In our first example, we will simply get the window size, and in our second example, we will get the window size on resizing. In order to get the height and width of the window, the step by step process is described as follows:
Example 1:
In the first example, we will get the width and height of the window.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<p>Screen width: {{ screenWidth }}</p>
<p>Screen height: {{ screenHeight }}</p>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
public screenWidth: any;
public screenHeight: any;
ngOnInit() {
this.screenWidth = window.innerWidth;
this.screenHeight = window.innerHeight;
}
}
Now our example 1 is ready to run. When we run this example, the following output will be generated:
Screen width: 1374
Screen height: 589
Example 2:
In our second example, we will get window size on resizing.
import { Component, OnInit, HostListener } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<p>Screen width: {{ screenWidth }}</p>
<p>Screen height: {{ screenHeight }}</p>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
public screenWidth: any;
public screenHeight: any;
ngOnInit() {
this.screenWidth = window.innerWidth;
this.screenHeight = window.innerHeight;
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.screenWidth = window.innerWidth;
this.screenHeight = window.innerHeight;
}
}
Now our example 2 is ready to run. When we run this example, the following output will be generated:
Screen width: 878
Screen height: 685
Leave a Reply