Nemanja G
Nemanja G

Reputation: 1850

Check window size Angular 2

I need to check the window size, if it is < 1400 px (laptops), what is the best way to do it?

If it is less than 1400 I would like to set a variable to true for example.

Upvotes: 1

Views: 13777

Answers (2)

Monika V
Monika V

Reputation: 15

HTML:

<div (window:resize)="onResize($event)">  your html here  </div>

JS:

onResize($event){
 this.myVariable = event.target.innerWidth > 1400 ? true : false;
}

Upvotes: 0

FatL
FatL

Reputation: 171

You can get these values like that :

constructor() {
  // User screen size
  const screenHeight = window.screen.height;
  const screenWidth = window.screen.width;

  // Actual space available in navigator
  const actualHeight = window.innerHeight;
  const actualWidth = window.innerWidth;
}

But this won't change if the user resize it's window.

You can get these new values by using a HostListener :

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.newInnerHeight = event.target.innerHeight;
  this.newInnerWidth = event.target.innerWidth;
}

onResize will be called when the navigator's window is resized. It may be very often, you may need a Subject to handle it.

Upvotes: 11

Related Questions