我找到了这个解决方案。有效吗?
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/