How to get height and width of device display in angular2 using typescript?

后端 未结 5 607
猫巷女王i
猫巷女王i 2020-12-13 01:50

I found this solution. Is it valid?

import {Component} from \'@angular/core\';
import {Platform} from \'ionic-angular\';

@Component({...})
export MyApp {
co         


        
5条回答
  •  春和景丽
    2020-12-13 02:26

    For those who want to get height and width of device even when the display is resized (dynamically & in real-time):

    • Step 1:

    In that Component do: import { HostListener } from "@angular/core";

    • Step 2:

    In the component's class body write:

    @HostListener('window:resize', ['$event'])
    onResize(event?) {
       this.screenHeight = window.innerHeight;
       this.screenWidth = window.innerWidth;
    }
    
    • Step 3:

    In the component's constructor call the onResize method to initialize the variables. Also, don't forget to declare them first.

    constructor() {
      this.onResize();
    }    
    

    Complete code:

    import { Component, OnInit } from "@angular/core";
    import { HostListener } from "@angular/core";
    
    @Component({
      selector: "app-login",
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    
    export class FooComponent implements OnInit {
        screenHeight: number;
        screenWidth: number;
    
        constructor() {
            this.getScreenSize();
        }
    
        @HostListener('window:resize', ['$event'])
        getScreenSize(event?) {
              this.screenHeight = window.innerHeight;
              this.screenWidth = window.innerWidth;
              console.log(this.screenHeight, this.screenWidth);
        }
    
    }
    

提交回复
热议问题