Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a function on page load, ANGULAR 2

I have a simple function, checking the width of the window and according to that value it stretches the content. But when I resize the page and reload the site, nothing happens until I resize the window. How do I call a function on page load in angular2?

My whole app.component.ts file:

import { Component } from '@angular/core';

@Component({
  templateUrl: './app.component.html'
})
export class appComponent {

  private checkScreenWidth() {
    if (window.innerWidth < 1000 && window.innerWidth > 499) {
      ...
    } else if (window.innerWidth < 500) {
      ...
    } else {
      ...
    }
  }
}
like image 533
J. Doe Avatar asked Jan 24 '26 11:01

J. Doe


1 Answers

You may import and implement the OnInit interface of angular2 core library and define its ngOnInit method after implementing the interface in the class. I guess it will do the job.

export class appComponent implements OnInit {
  private checkScreenWidth() {
    if (window.innerWidth < 1000 && window.innerWidth > 499) {
      ...
    } else if (window.innerWidth < 500) {
      ...
    } else {
      ...
    }
  }
  ngOnInit() {
    this.checkScreenWidth();
  }

}
like image 85
Peter Avatar answered Jan 27 '26 01:01

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!