如何使用打字稿在angular2中获取设备显示的高度和宽度?

新手上路,请多包涵

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

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

该解决方案适用于离子 2。我也可以用于 angular 2 吗?

请建议我正确的方法。

原文由 Harish Mahajan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 508
2 个回答

我找到了解决方案。答案很简单。在您的构造函数中编写以下代码。

 import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
    // Declare height and width variables
    scrHeight:any;
    scrWidth:any;

    @HostListener('window:resize', ['$event'])
    getScreenSize(event?) {
          this.scrHeight = window.innerHeight;
          this.scrWidth = window.innerWidth;
          console.log(this.scrHeight, this.scrWidth);
    }

    // Constructor
    constructor() {
        this.getScreenSize();
    }

}

====== 工作代码(另一个) ======

 export class Dashboard  {
 mobHeight: any;
 mobWidth: any;
     constructor(private router:Router, private http: Http){
        this.mobHeight = (window.screen.height) + "px";
        this.mobWidth = (window.screen.width) + "px";
          console.log(this.mobHeight);
          console.log(this.mobWidth)
     }
}

原文由 Harish Mahajan 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于这种情况,您可以使用 typescript getter 方法。像这样

public get height() {
  return window.innerHeight;
}

public get width() {
  return window.innerWidth;
}

并在这样的模板中使用它:

 <section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>

打印值

console.log(this.height, this.width);

您不需要任何事件处理程序来检查窗口的大小调整,此方法每次都会自动检查大小。

原文由 Rohan Gayen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进