Angular 13 Detect Width and Height of Screen Tutorial

Replace TypeScript Template
Import HostListener API from ‘@angular/core’ package deal, outline variables get display width and getScreenHeight, use the HostListener to bind window to resize occasion to get the display measurement and width on window resize.

Replace the code in src/app/app.element.ts file.

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

@Part({
  selector: 'app-root',
  templateUrl: './app.element.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

Replace HTML Template
On this step, you must open the angular HTML template file and outline the variables utilizing the double curly braces to print the display or window measurement on the browser.

Please replace the code in src/app/app.element.html file.

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

Exit fullscreen mode

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

Add a Comment

Your email address will not be published. Required fields are marked *