Angular window resize event
<div (window:resize)="onResize($event)"
onResize(event) {
event.target.innerWidth;
}
or using the HostListener decorator:
@HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}
Supported global targets are window
, document
, and body
.
Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.
How to trigger window resize event in Angular
You can trigger window.resize
event by
window.dispatchEvent(new Event('resize'));
And for listening to window.resize
, use HostListener as below example:
@HostListener('window:resize', ['$event'])
sizeChange(event) {
console.log('size changed.', event);
}
live demo
How I can detect window resize instantly in angular 2?
You could just put handler on resize
event over window
object, but this will allow you to put only single resize
event, latest registered event on onresize
will work.
constructor(private ngZone:NgZone) {
window.onresize = (e) =>
{
//ngZone.run will help to run change detection
this.ngZone.run(() => {
console.log("Width: " + window.innerWidth);
console.log("Height: " + window.innerHeight);
});
};
}
To make it more angular way use @HostListener('window:resize')
inside your component, which will allow to call your resize function(on which HostListner
decorator has been mount) on resize
of window.
@HostListener('window:resize', ['$event'])
onResize(event){
console.log("Width: " + event.target.innerWidth);
}
Angular SSR window resize event
<div (window:resize)="onResize($event)"
Method:
onResize(event) {
event.target.innerWidth;
}
or
@HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}
Supported global targets are window
, document
, and body
.
Angular resize service
You don't need that much code actually, you can just assign the true
or false
directly in the service to an observable, to which you in the component subscribe. Assumingly you want to show different content in template depending on mobile/desktop view, so it's a perfect scenario to use the async
pipe!
If you need the true
/false
in the component ts, you can of course subscribe to it, but remember to unsubscribe if that is the path you are taking!
Anyways, I suggest the following...
SERVICE:
isMobile$ = fromEvent(window, 'resize').pipe(
startWith(window), // to have an initial value, can be any value
mapTo(window), // map to window object instead (so we can have the initial value!)
throttleTime(500),
debounceTime(500),
map((window: Window) => {
if (window.innerWidth < PHONE_SIZE.width && window.innerHeight < PHONE_SIZE.height) {
return true;
}
return false;
})
);
And in the component you simply do....
isMobile$ = this.resizeService.isMobile$;
Then either use the async
pipe or subscribe!
HERE'S A DEMO - here only the screen width is taken into consideration for easy testing :)
Angular 6 service resize event
In this case, you may subscribe to 'window:resize' in app.component
and have a service which will handle all the data. Depends on what do you want to do with it.
just for example if you want just to store(and share) the window size you should have a service:
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
@Injectable() // could be @Injectable({ providedIn: 'root' }) in 6+ version
export class ResizeService {
currentSize$: Subject<number|string> = new Subject<number|string>();
getSize(): Observable<number|string> {
return this.currentSize$.asObservable();
}
setSize(size: number|string): void {
this.currentSize$.next(size);
}
}
Then in your app.component.ts
;
import { Component } from '@angular/core';
import { ResizeService } from '<path/to/service>';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private resizeService: ResizeService) {}
resizeHandler($event): void {
this.resizeService.setSize($event.target.innerWidth);
}
}
In any component that you want to get these values:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, Observable } from 'rxjs'
import { takeUntil } from 'rxjs/operators';
import { ResizeService } from '<path/to/service>';
@Component({
selector: 'app-my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit, OnDestroy {
private unsubscribeHelper$: Subject<void> = new Subject<void>();
public size: number | string;
constructor(private resizeService: ResizeService) {}
ngOnInit(): void {
this.resizeService.getSize().pipe(takeUntil(this.unsubscribeHelper$))
.subscribe((size: number | string) => this.size = size);
}
ngOnDestroy(): void {
this.unsubscribeHelper$.next();
this.unsubscribeHelper$.complete();
}
}
So far this is the most universal solution to cover most of cases when you need to process data through the service and share it among the application
Angular 7 window resize event not running in service
A HostListener
is what it says it is. It listens for events on the host component. Just the convenience that you can use the extra window
, document
or body
binding for a global listener, does not make the HostListener work inside a service.
For this you either have to use the Renderer
, the simple window.addEventListener
or the rxjs fromEvent(window)
.
Another way to do it, is to add the @HostListener()
to the AppComponent (and only there), and let it emit the service observable from there.
Related Topics
Obtain Form Input Fields Using Jquery
Can You Determine If Chrome Is in Incognito Mode via a Script
Ecmascript 6 Features Available in Node.Js 0.12
Get the Content (Text) of an Url After JavaScript Has Run with PHP
CSS Delivery Optimization: How to Defer CSS Loading
How to Move a Div with Arrow Keys
How to Emulate an HTML Input "Maxlength" Attribute on an HTML Textarea
How to Clear a Chart from a Canvas So That Hover Events Cannot Be Triggered
Screen Scraping from a Web Page with a Lot of JavaScript
How to Conditionally Add Attributes to React Components
Replace Multiple Whitespaces with Single Whitespace in JavaScript String
How to Clone HTML Element Objects in JavaScript
Http Get Request in Node.Js Express
How to Assign JavaScript Variable Value to PHP Variable
Resize a Div on Border Drag and Drop Without Adding Extra Markup
Accessing Localstorage from a Webworker
How to Submit 2 Forms in One Page with a Single Submit Button