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?

1
  • I'm not sure that would work. All your code is loaded after the document was loaded. See this fiddle 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. Commented Dec 2, 2015 at 6:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.