angular - 如何使用 typescript 在angular2中获取设备显示的高度和宽度?

标签 angular typescript

我找到了这个解决方案。有效吗?

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

@Component({...})
export MyApp {
constructor(platform: Platform) {
  platform.ready().then((readySource) => {
    console.log('Width: ' + platform.width());
    console.log('Height: ' + platform.height());
  });
 }
}

此解决方案适用于 ionic 2。 我也可以用于 Angular 2 吗?

请建议我正确的方法。

最佳答案

对于那些想要在显示调整大小(动态和实时)时获取设备的高度和宽度的用户:

  • 第 1 步:

在该组件中执行:import { HostListener } from "@angular/core";

  • 第 2 步:

在组件的类主体中写入:

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

在组件的constructor 中调用onResize 方法来初始化 变量。另外,不要忘记先声明它们。

constructor() {
  this.onResize();
}    

完整代码:

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);
    }

}

关于angular - 如何使用 typescript 在angular2中获取设备显示的高度和宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888768/

相关文章:

angular - 图片裁剪后如何将base 64转换为图片文件,需要上传服务器

angularjs - 在 Angular 分量上触发 $scope.$watch

typescript - 我可以为以编​​程方式生成的 TypeScript 接口(interface)/类型的键添加前缀或后缀吗?

javascript - Angular 2 ng-model-options ="{updateOn: ' 改变模糊'}”

javascript - angular2 中的变化检测是否总是从根组件开始?

javascript - component.html 中的变量在 Angular 6 中未定义

Angular 6 : Adding @Input to component doesn't work

javascript - 我的标题在 http 帖子错误中为 null Angular 6

angular - 使用 Http JSON AngularJS 2 时出错

typescript - 确定类型是 'string' 文字、 'number' 文字还是 'string | number' 文字