Detect Width and Height of Screen in Angular 13

I was recently given a task for creating a flexible layout, but I was not permitted to use CSS media queries; instead, I had to use the *ngIf directive whenever the window size changed.

So I made the decision to use the HostListener API to go through the Angular window size detecting process.

Depending on the particular screen size, you could occasionally need to conduct development chores. These jobs could include anything from creating a class to adding style to calling any function.

Update TypeScript Template

Defining variables and importing the HostListener API from the @angular/core package To obtain the screen size and breadth upon window resizing, use the HostListener to link the window to the resize event.

Update the code in demo.component.ts file

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

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss'],
})
export class DemoComponent implements OnInit {
 getWindowWidth: number = 0;
 getWindowHeight: number = 0;

  ngOnInit() {
    this.getWindowWidth = window.innerWidth;
    this.getWindowHeight = window.innerHeight;
  }

  @HostListener('window:resize', ['$event'])
  onWindowResize() {
    this.getWindowWidth = window.innerWidth;
    this.getWindowHeight = window.innerHeight;
  }
}
Update HTML Template

To print the screen or window size on the browser, you must open the angular HTML template file and declare the variables using double curly brackets.

Update the code in demo.component.html file.

<section>
  <div class="text-center mt-5">
    <h4>Window width = {{ getWindowWidth }}</h4>
    <h4>Window height = {{ getWindowHeight }}</h4>
  </div>
</section>
Start Angular App
ng serve
Conclusion

With the help of this Angular screen size detect example, we have learnt how to acquire responsive screen sizes when a user resizes or changes the window size.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories