1

I'm currently using the Angular @HostListener to get the current width of the viewport onResize() like this:

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

But I also need a way to set this.width onLoad() of the component (in the constructor or at least in the ngOnInit() lifecycle).

I didn't found a way to do this with the HostListener. Is there a good alternative to get the current width of the viewport (on resize and on load) and react to it?

My goal is the set the maxWidth of a Leaflet-PopUp on mobile viewport sizes.

Codehan25
  • 2,704
  • 10
  • 47
  • 94

4 Answers4

0

If in case you are using bootstrap you can use bootstrap CSS media queries,

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

If otherwise what you have tried is right way without using external dependencies.

Sasi Kumar M
  • 2,440
  • 1
  • 23
  • 23
  • I need a way to do it with Angular, because the leaflet library is generating it's own CSS based on properties like: L.popup({ maxWidth: 600, maxHeight: 500 }, marker).. I also want to avoid the use of !important in my CSS files.. – Codehan25 Dec 03 '19 at 08:35
0

simplay you can just call the method it selft as you dont use the event object so

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

demo

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
0

If you need it in constructor you can inject DOCUMENT built-in token to get document. It has defaultView property which is current window or null. If it's not null you can get its width:

constructor(@Inject(DOCUMENT) {defaultView}: Document) {
  this.width = defaultView ? defaultView.innerWidth : 0;
}
waterplea
  • 3,462
  • 5
  • 31
  • 47
0
...

clientWidth: number;

constructor(){
   this.initMethod();
}

initMethod() {
    this.clientWidth = (document.childNodes[1] as any).clientWidth;
}

Its another method instead of accessing through a sepperate @Viewchild or a @HostListener to get the current width

dev.ws
  • 89
  • 4