Angular 13 Detect Width and Height of Screen Tutorial

Dhanush - May 11 '22 - - Dev Community

Update TypeScript Template
Import HostListener API from @angular/core package, define variables get screen width and getScreenHeight, use the HostListener to bind window to resize event to get the screen size and width on window resize.

Update the code in src/app/app.component.ts file.

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  public getScreenWidth: any;
  public getScreenHeight: any;

  ngOnInit() {
      this.getScreenWidth = window.innerWidth;
      this.getScreenHeight = window.innerHeight;
  }

  @HostListener('window:resize', ['$event'])
  onWindowResize() {
    this.getScreenWidth = window.innerWidth;
    this.getScreenHeight = window.innerHeight;
  }

}
Enter fullscreen mode Exit fullscreen mode

Update HTML Template
In this step, you have to open the angular HTML template file and define the variables using the double curly braces to print the screen or window size on the browser.

Please update the code in src/app/app.component.html file.

<div class="container text-center mt-5">
  <p>Window width: <strong>{{ getScreenWidth }}</strong></p>
  <p>Window height: <strong>{{ getScreenHeight }}</strong></p>
</div>
Enter fullscreen mode Exit fullscreen mode

Reference:
https://www.positronx.io/angular-detect-width-and-height-of-screen-tutorial/

. . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player