What is the best way to retrieve the height and width of a device's display in Angular 2 using Typescript

I came across this code snippet. Do you think it's valid?

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

This code is specifically for Ionic 2. Can it also be used for Angular 2?

Please advise me on the proper approach for this scenario.

Answer №1

For individuals looking to obtain the height and width of their device even when the display is adjusted (dynamically & in real-time):

  • Step 1:

In the specified Component, include:

import { HostListener } from "@angular/core";

  • Step 2:

Within the component's class body, add the following:

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

Within the component's constructor, invoke the onResize method to initialize the variables. Ensure they are declared first as well.

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

}

Answer №2

I have discovered the solution to your problem and it is quite simple. All you need to do is add the following code snippet to your constructor.

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Make sure to import this line at the beginning 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 {
    // Define variables for height and width
    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 function
    constructor() {
        this.getScreenSize();
    }


}

====== Working Code (Another) ======

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

Answer №3

class DataBoard {
    windowHeight: any;
    windowWidth: any;
    constructor() {
        this.windowHeight = (window.screen.height) + "px";
        this.windowWidth = (window.screen.width) + "px";
    }
}

Answer №4

To handle this scenario, you can utilize the typescript getter method. Here's an example:

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

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

Then, you can use these getters in your template like so:

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

Display the values:

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

You don't need to create an event handler to monitor window resizing as this method will automatically check the size every time.

Answer №5

Remember, in case you wish to test this specific component, make sure to inject the window. Utilize the @Inject() method to inject the window object by assigning it a string token as shown in this helpful article

Answer №6

It's been suggested that injecting DOCUMENT into the constructor is the best practice to ensure compatibility with both browser and server-side rendering platforms. The use of the global DOM reference to window may only work for browser-based rendering. To access the window object, you can utilize DOCUMENT:

@Inject(DOCUMENT) private _document: Document

console.log('window height ', this._document.defaultview.innerHeight);
console.log('window height ', this._document.defaultview.innerWidth);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element: <span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight"> {{ list}} < ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

What is the best way to handle success data in React Query?

Currently, I have an API call function (using httpClient as axios instance) interface IRegisterResponse { accessToken: string; } export const register = async ({ name, password, token, }: IRegisterParams) => await httpClient.post<IRegiste ...

Encountering an issue with Angular2 where it is unable to load a JSON file, presenting the error message: "Cannot resolve all parameters

I've been trying to incorporate a json file into my Angular app, but I can't seem to pinpoint the issue. The error message keeps indicating that it cannot resolve all parameters of my component. (I had no trouble loading data directly from the c ...

Steps for assigning the TAB key functionality within a text area

Is there a way to capture the TAB key press within a text area, allowing for indentation of text when the user uses it? ...

Struggling to tally the entries and authenticate logins within Ionic 3 and Angular

In my application, users register by providing their email and password, which is then stored in a SQLite database. When the user attempts to log in using the same credentials, they should be redirected to the home page upon successful login. I am facing ...

Iterate through each item in an object using Angular

I attempted to utilize a forEach loop, but it's indicating that it's undefined for some reason. Here is my code snippet: var array: MoneyDTO[] = prices array.forEach(function (money: MoneyDTO) { if (money.currency == 'QTW& ...

Creating a dynamic table with columns of fixed width in Angular on the fly

I am struggling to create a data table with fixed column widths (20% each). I have incorporated div elements in my table structure to enable dynamic row creation using Angular, but this has caused some design issues. My goal is for all rows to occupy 100% ...

Having trouble iterating over an array in Angular's TypeScript

I've been attempting to loop through an array of objects in TypeScript, but encountered the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined TypeError: Cannot read property 'fo ...

Determine the data type of an individual attribute within a collection of classes

I am working with a series of classes that have a body property defined within them. Here is an example: class Foo { body: {foo: string} constructor(body: Record<string, string>) { this.body = { foo: body.foo } } } class Bar { body: {ba ...

Issue: ng test encountered a StaticInjectorError related to FormBuilder

I recently started using ng test to run tests on my Angular application. I utilized the Angular-Cli tool to create modules and components, and the .spec.ts files were generated automatically. During one of the tests, I encountered the following error: ...

The module declaration can be found in two locations

After developing an app in debug mode and confirming that it functions properly on a device, I encountered an error while trying to create a release build: https://i.stack.imgur.com/ztQpD.png The process involved generating a page using 'ionic gener ...

Having Trouble with Ionic 2's Loading Controller

In my attempt to utilize the recently added LoadingController in this scenario: let loading=this.load.create({ content: "Connexion au serveur Migal en cours..." }); loading.present(); this.http.get(this.urlCheckerForm.value.migalUrl+'/action/Mobi ...

Angular button press

Recently, I started learning Angular and came across a challenge that I need help with. Here is the scenario: <button *ngIf="entryControlEnabled && !gateOpen" class="bottomButton red" (click)="openGate()">Open</button> <button *ngIf ...

Which types of mouse events are compatible with Angular2?

Exploring mouse events in Angular2 has sparked my curiosity. I have implemented the click event, but now I wonder what other mouse events are available, such as mouseover. Where can I find a comprehensive list of mouse events supported by Angular2? The o ...

Guide on accessing an element from a predicate object in Typescript while using Angular

I'm trying to wrap my head around how to access an element that exists on an object of a specific type but is defined as a type predicate. For example, let's say we have a Team defined as: let team$: Observable<ErrorModel | Team> The res ...

Sending the :id parameter to the Service component

In the early days of my Angular journey, I have a simple question. Currently, I am utilizing the WordPress REST API to showcase a list of posts from a specific category by using posts?categories={ID HERE}. However, I am facing an issue in passing the ID f ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Encountering an ECONNREFUSED error upon upgrading from Next.js 12 to 13

After upgrading from Nextjs 12 to 13, I am experiencing issues where every time I try to run the application, I encounter ECONNREFUSED to my local host but the port seems to keep changing. This results in the application not rendering properly. > <a ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...