Utilizing the Angular @HostListener to retrieve the current viewport width upon loading - a simple guide

Currently, I am utilizing the Angular @HostListener to retrieve the current width of the viewport onResize() in the following manner:

  @HostListener('window:resize', ['$event'])
  onResize(event?) {
    window.innerWidth <= 400 ? this.width = 200 : this.width = 400;
  }

However, I also require a method to set this.width onLoad() of the component (either in the constructor or during the ngOnInit() lifecycle).

I have not discovered a way to achieve this using HostListener. Is there an effective alternative to obtain the current viewport width (both on resize and onLoad) and respond accordingly?

My objective is to define the maxWidth of a Leaflet-PopUp for mobile viewport sizes.

Answer №1

If you happen to be utilizing bootstrap, consider employing bootstrap CSS media queries,

https://getbootstrap.com/docs/4.0/layout/overview/

If not, then your current approach may be the correct way without relying on external dependencies.

Answer №2

Simply put, you can directly call the method itself without utilizing the event object.

  ngOnInit() {
    console.log(this.width);
    this.onResize();
    console.log(this.width);
  }

Check out the demo 🔥

Answer №3

In order to access the document in a constructor, you can inject the built-in token DOCUMENT to retrieve the document object. The DOCUMENT object has a defaultView property which refers to the current window or is null. If it is not null, you can obtain its width as follows:

constructor(@Inject(DOCUMENT) {defaultView}: Document) {
  this.width = defaultView ? defaultView.innerWidth : 0;
}

Answer №4

...

clientHeight: number;

constructor(){
   this.initialize();
}

initialize() {
    this.clientHeight = (document.childNodes[1] as any).clientHeight;
}

Instead of using a separate @ViewChild or @HostListener, this method provides an alternative way to retrieve the current height.

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

Is there a way to disable tslint warnings for npm linked packages?

Currently, I am in the process of developing a set of Angular/TypeScript components within an application that utilizes this package. To facilitate the sharing of these components, I have utilized npm link. However, upon building the project, I encountered ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

Vue component fails to trigger upon receiving the 'mouseleave' event

I am currently working on a navbar with dynamic component navigation, where hovering over a navbar-link should display the corresponding component and hiding it when the mouse leaves. Although the components are displayed correctly upon hover, they do not ...

Is there a way to view 2D flat items in 3D using either babylonjs or threejs?

I am currently utilizing fabricJS and have created a variety of random drawings (such as circles, squares, and polygon shapes) on a canvas shaped like a rectangle object (Base). My goal is to display all these drawings engraved on the main rectangle objec ...

Exploring the functionality of ngTemplateOutlet, the implementation of @ContentChild, and the benefits of using ng

Lately, I've been dedicating more time to grasp the concepts presented in the blog post titled Creating Reusable Components with NgTemplateOutlet in Angular If you want to see the code in action, it's available on stackblitz. Within the UsageEx ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...

Struggling with object type casting in Typescript

Having issues with casting objects from an HTTP API response to Typescript. I am trying to cast the json data to a Typescript object using the "as" keyword or <Type >, but it's not working as expected. r.forEach(entry => { entry.creatio ...

The ExpressJS EJS issue arises when trying to access a property that is undefined

I'm new to NodeJS and seeking assistance. I am working on a website where users can promote their virtual conferences for others to see. I have set up a form with the POST method, where the data gets pushed into an array and then displayed in an EJS f ...

Eliminate an item from an array that contains multiple arrays

I am working with a multidimensional array that looks like this: myArray = [ ["ooooh", "that"], ["dog ", "of"], ["mine", "word...."] ] My goal is to remove the array item: ["ooooh", "that"] Although I know that element 0 is "ooooh" and element 1 is ...

Looking to transfer data between pages using node.js and ejs for database access?

I am aiming to showcase the logged in username and quiz points on each page after the user logs in, and to increase the user's score when quiz answers are correct. I'm considering creating a straightforward JavaScript-based quiz, and then updati ...

Testing a stateless React component with withRouter() using Enzyme and ways to pass the match parameter

I have a React functional component that I am testing and it is wrapped in withRouter from react-router-dom. The component's code structure is shown below. import * as React from 'react'; import { Switch, Route, withRouter, RouteComponentPr ...

Issue with sending array as parameter in ajax call in Laravel

I am currently encountering an issue while attempting to pass an array through an AJAX request. <input type="text" name="item_name[]"> <input type="text" name="address"> $(document).on('click', '#save_info', function () { ...

Using JQuery to enable the movement of divs on a screen through clicking and dragging, without the use of

Recently, I've been experimenting with a small project involving draggable divs. However, the code I've written doesn't seem to be functioning properly, causing JQuery to become unresponsive. Is there an alternative method that is simple an ...

Steps for updating the value of angular inputs within a function

When a card is selected on the page below, the input values should be updated with information from a JSON object. Here is the JSON data: { "status": true, "data": [ { "id": 1, "pessoa_id": 75505 ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Chrome does not support top.frames functionality

I have three HTML pages: main.html, page1.html, and page2.html. I am displaying page1.html and page2.html within main.html using the code below. <!DOCTYPE html> <html> <frameset frameborder="1" rows="50%, *"> <frame name="f ...

The mistake is indicating the npm title of a package that is not present

https://i.sstatic.net/5bywN.png An issue has arisen - the module cannot be found, even though such a module does not actually exist. The correct module name should be babel-plugin-proposal-class-properties (and the error is showing as 'babel-plugin-t ...

Is it possible to update the parent state from a child component using the useEffect hook in React?

In a child component, there are buttons that, when clicked, toggle corresponding state values between true and false. This child component also contains a useEffect hook with dependencies on all these state values. When a button is clicked, the hook calls ...

Chrome's Ctrl-Shift-N event binding

I have implemented jQuery.hotkeys to handle keyboard events. Currently, I am attempting to bind the combination of Ctrl+Shift+N $(document).bind('keydown', 'ctrl+shift+n', function(e) { e.preventDefault(); alert('Ctrl+Shi ...