How to specifically activate window resize when the width changes

I am looking to implement custom styling on an element based on the current screenWidth of the window.

This can be achieved using the following @HostListener:

 @HostListener('window:resize', ['$event'])
  public resize() {

   // Apply styles here depending on current window.innerWidth...

  }

However, I only want the resize method to be triggered when the width of the window changes, and not when the height changes.

Currently, the resize method is called even if the user changes the window height, causing issues with my styling logic!

My question is: Is there a way in Angular to create something like ('window:resizeX') that will call resize() only when the window width changes, ignoring any changes in window height?

Answer №1

One effective way to handle window resize events is by using the following code snippet:

fromEvent(window, 'resize')
  .pipe(map(() => window.innerWidth), distinctUntilChanged())
  .subscribe(() => this.onResize());

If you wish to optimize this further, you can incorporate auditTime() as shown below:

fromEvent(window, 'resize')
  .pipe(auditTime(100), map(() => window.innerWidth), distinctUntilChanged())
  .subscribe(() => this.onResize());

This will ensure that your method is not triggered more frequently than every 100ms.

Answer №2

There are two main methods commonly used to observe resizing:

  1. Utilizing the fromEvent method with window as the target
  2. Implementing the @HostListener decorator for 'window:resize' events

Each approach offers unique advantages depending on individual preference and specific use case needs.

To explore a comparison between these techniques, refer to fromevent window vs hostlistener.

If you encounter an issue related to screen resizing, Oleg suggested a solution involving the fromEvent operator. Alternatively, you can consider resolving it using the HostListener approach, similar to the example below:

private lastScreenWidth;
....

ngAfterViewInit(){
    this.lastScreenWidth = window.innerWidth;
}

@HostListener('window:resize', ['$event'])
private resize(event) {
    if (event.target.innerWidth !== this.lastScreenWidth) {
        // Implement actions based on window width changes
        this.lastScreenWidth = event.target.innerWidth;
    }
}

Answer №3

Oleg Postoev has the correct idea, that is the most effective approach.

This particular version will only trigger if the width remains constant for a short period (800ms);

fromEvent(window, 'resize').pipe(
  debounceTime(800),
  tap((event: UIEvent) => {
    const width = event.target['innerWidth'];
    // PERFORM AN ACTION
  }, takeUntil(this.unsubscribe$)) // CLEANUP
).subscribe();

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

TS-2304 Error - 'Iterable' not found in TypeScript when trying to import 'jquery' into a '.ts' file

Currently, I am utilizing TypeScript version 2.4 in Visual Studio Code for development. My approach involved installing jQuery via NPM using the given command: npm install --save @types/jquery Subsequently, I obtained the source code for the jquery modul ...

Transforming every piece of TypeScript code into JavaScript on the server-side

I'm relatively new to developing Node.js applications for production. I've created an app using TypeScript for the backend of my Node.js project. Currently, in the package.json file, I have the following script section: "scripts": { ...

Despite the presence of the element, ngIf fails to render it on the screen

{{ element.number }} <div *ngIf="element.number"> 123 </div> Even though the server is sending the number, it's not displaying 123 as expected. Tried updating the ngIf to: *ngIf="element?.number" What could ...

Invoking a function in an Angular 4 component using a <td> element

Take a look at this block of code: personListComponent.html <tr *ngFor="let person of personService.getPersons()"> <td (onShow)="getCountry(person)">{{person.name}}</td> <td>{{country}} </tr personListComponent.ts ...

What is the proper way to define the type of an object when passing it as an argument to a function in React using TypeScript?

I'm struggling to figure out the appropriate type definition for an Object when passing it as an argument to a function in React Typescript. I tried setting the parameter type to "any" in the function, but I want to avoid using "any" whenever passing ...

How to refresh a page manually in Angular 2

How can I have a page in Angular reload only once when a user visits it? This is my attempt: In the homepage component, I added the following code: export class HomepageComponent implements OnInit { constructor() { } ngOnInit() { location.relo ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

The module '@/assets/icons/pay/pay-success.png' cannot be located, along with its corresponding type declarations.ts

Recently, I encountered an issue while trying to import a png image in my Typescript code. Here is the snippet of code that caused the error: import paySuccessIcon from "@/assets/icons/pay/pay-success.png"; When I tried to import the image, Visual Studio ...

What could be causing Bootstrap to fail in my fresh Angular project?

Upon creating a fresh angular project, I proceeded to install bootstrap using npm. Once it was successfully installed in my node_modules folder, I added it to my angular.json file. "styles": [ "/node_modules/bootstrap/dist/css/ ...

Creating a custom URL in a React TypeScript project using Class components

I have been researching stack overflow topics, but they all seem to use function components. I am curious about how to create a custom URL in TypeScript with Class Components, for example http://localhost:3000/user/:userUid. I attempted the following: The ...

Receiving warnings during npm installation and encountering difficulties with fixing issues using npm audit fix

Currently, I am working on developing an Angular application with a .NET Core Web API integration. Upon cloning the repository, I attempted to execute 'npm install' for the Angular application, but encountered an unexpected error: npm install n ...

What is the process for transforming a JSON object into a TypeScript interface?

After receiving a JSON output from an api: { "id": 13, "name": "horst", "cars": [{ "brand": "VW", "maxSpeed": 120, "isWastingGazoline": true ...

Tips for parsing a JSON file within an Ionic app?

I need assistance with reading a JSON file in my Ionic app. I am new to this and unsure about how to proceed. In this scenario, there is a provider class where I fetch data from import { Injectable } from '@angular/core'; import { Http } from ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Verify whether a web application is equipped with React, Angular, or Vue

Is there an easy way to identify the client-side libraries used by an application if they are minified or compressed? While examining all the JavaScript sent from the server to the client, it can be challenging to determine if one of the top three popular ...

Does manipulating the context before retrieving it within a custom ContextProvider adhere to best practices?

In my React application, I have a custom ContextProvider component called RepositoryContext. This component requires a specific ID to be set inside it in order to perform CRUD operations. Here is a snippet of the code: import React, { Dispatch, PropsWithCh ...

What is the best way to assign ngModel to dynamically inserted input rows in Angular 4+ (specifically in a mat-table)?

Just a quick question - how can I add ngModel to dynamically added new input rows? I have a Mat table with multiple rows and an "add element" method that adds a new row every time a button is clicked. This way, I want to bind the user-entered values and se ...

Different Approaches for Handling User Interactions in Angular Instead of Using the Deferred (Anti-?)Pattern

In the process of developing a game using Angular, I have implemented the following mechanics: An Angular service checks the game state and prompts a necessary user interaction. A mediator service creates this prompt and sends it to the relevant Angular c ...

The directive for angular digits only may still permit certain characters to be entered

During my exploration of implementing a digits-only directive, I came across a solution similar to my own on the internet: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appOnlyDigits]' ...