Angular – Responsiveness with @HostListener()
This is a short example of how to programmatically build responsiveness into a component. So when the user changes the size of the screen, the listener will get the dimensions in real-time so you can adjust columns or text sizes accordingly.
Import the following into your component.
import { Component, OnInit} from '@angular/core';
import { HostListener } from '@angular/core';
First Scenario – When the component is first rendered
On ngOnInit() get the current size of the browser window.
public windowSize: any;
private screenWidth:number = window.innerWidth;
ngOnInit(): void {
this.windowSize = 3;
if (this.screenWidth >= 1700) {
this.windowSize = 'lg';
}
else if (this.screenWidth > 1000 && this.screenWidth < 1700) {
this.windowSize = 'md';
}
else if (this.screenWidth <= 1000) {
this.windowSize = 'sm';
}
else {
this.windowSize = 'xs';
}
console.log('Window Size ', this.windowSize);
}
Second Scenario – During the user session
For changes that happen during the user session on the page using the @HostListener() decorator.
@HostListener('window:resize', ['$event'])
onResize(event?) {
if (event.target.innerWidth >= 1700) {
this.windowSize = 'lg';
}
else if(event.target.innerWidth > 1000 && event.target.innerWidth < 1700)
{
this.windowSize = 'md';
}
else if (event.target.innerWidth <= 1000) {
this.windowSize = 'sm';
}
else {
this.windowSize = 'xs';
}
console.log('Window Size ', this.windowSize);
}