Как получить высоту и ширину отображения устройства в угловом2 с помощью машинописного текста?
Я нашел это решение. Это действительно?
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?
Пожалуйста, предложите мне правильный способ сделать это.
Ответы
Ответ 1
Я нашел решение. Ответ очень простой. напишите приведенный ниже код в своем конструкторе.
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)
}
}
Ответ 2
Для тех, кто хочет получить высоту и ширину устройства, даже если размер экрана изменен (динамически и в режиме реального времени):
В этом компоненте выполните: import { HostListener } from "@angular/core";
В теле класса компонента напишите:
@HostListener('window:resize', ['$event'])
onResize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
}
В компоненте 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);
}
}
Ответ 3
export class Dashboard {
innerHeight: any;
innerWidth: any;
constructor(private router: Router, private http: Http) {
this.innerHeight = (window.screen.height) + "px";
this.innerWidth = (window.screen.width) + "px";
}
}
Ответ 4
Имейте в виду, если вы хотите протестировать этот компонент, вам нужно будет вставить окно. Используйте функцию @Inject(), чтобы ввести объект окна, называя его с помощью символа строки, как показано в этом дубликате.