Peter
Peter

Reputation: 3603

Get initial resize of window for Angular2 app component

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?

Upvotes: 3

Views: 7711

Answers (3)

acumartini
acumartini

Reputation: 411

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

Upvotes: 2

Natarajan Ganapathi
Natarajan Ganapathi

Reputation: 575

export class Application implements OnInit {
    ngOnInit() {
        window.onresize = this.onWindowLoadOrResize;
        this.onWindowLoadOrResize();
    }
    private onWindowLoadOrResize() {
      //TODO: your logic        
    }
}

Upvotes: 2

jornare
jornare

Reputation: 2893

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.

Upvotes: 3

Related Questions