3

In my app.html I have:

<div id="wrapper" 
    (document:load)="onWindowLoadOrResize($event)" 
    (window:resize)="onWindowLoadOrResize($event)">

This is used to set the height on the css for a content div. The resize is working fine, but it does not fire initially on the page load. The document:load does not fire at all. What is the best way to run code that will see the initial size of the window?

Peter
  • 3,563
  • 5
  • 30
  • 43
  • I'm not sure that would work. All your code is loaded after the document was loaded. See this [fiddle](http://jsfiddle.net/j29b8f4t/1/) to see what's going on. The first event listener runs, the second one doesn't, so it's happening the same in your code. – Eric Martinez Dec 02 '15 at 06:13

3 Answers3

3

At this point in your application, document.load is already fired. Easiest for you would probably be to do call the resizing function from your app-components constructor. At this point your DOM is ready, and the application is firing up. Also, you should assign the height value to a property in your app that the template can bind to rather than do DOM manipulation directly.

jornare
  • 2,903
  • 19
  • 27
2

export class Application implements OnInit {
    ngOnInit() {
        window.onresize = this.onWindowLoadOrResize;
        this.onWindowLoadOrResize();
    }
    private onWindowLoadOrResize() {
      //TODO: your logic        
    }
}
Natarajan Ganapathi
  • 551
  • 1
  • 7
  • 19
2

I was faced with a similar problem. Here is the solution I came up:

ngOnInit() {
  console.log('document.load: ', window.innerWidth);
}

@HostListener('window:resize', ['$event'])
onResize(event) {
  console.log('resize event: ', event.target.innerWidth);
}

Reference: Angular2 get window width onResize

Community
  • 1
  • 1
acumartini
  • 411
  • 6
  • 10