3

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 {
      ...
    }
  }
}
4
  • 3
    Call it in ngOnInit or ngAfterViewInit? Have you read up on the lifecycle hooks? What have you tried? Commented Nov 26, 2016 at 22:35
  • @jonrsharpe I just tried to call it in component, but didn't work as it supposed to. I will check on google ngOnInit and will let u know bout the progress. Commented Nov 26, 2016 at 22:36
  • 2
    angular.io/docs/ts/latest/guide/lifecycle-hooks.html Commented Nov 26, 2016 at 22:37
  • @jonrsharpe It works, thank u. Commented Nov 26, 2016 at 22:40

2 Answers 2

2

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();
  }

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

2 Comments

on init function runs during page loads
@DhireshBudhiraja That's what he needs: 'How do I call a function on page load in angular2?' Read the question. Your downvote is unjust!
0

First of all import OnInit from '@angular/core'module and then call a method inside ngOnInit which you want to call on load its like ng-init from angularjs.

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

 ngOnInit() {
    this.checkScreenWidth();
  }

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.