最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Executing a function on page load, ANGULAR 2 - Stack Overflow

programmeradmin1浏览0评论

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 appponent.ts file:

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

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

  private checkScreenWidth() {
    if (window.innerWidth < 1000 && window.innerWidth > 499) {
      ...
    } else if (window.innerWidth < 500) {
      ...
    } else {
      ...
    }
  }
}

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.ponent.ts file:

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

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

  private checkScreenWidth() {
    if (window.innerWidth < 1000 && window.innerWidth > 499) {
      ...
    } else if (window.innerWidth < 500) {
      ...
    } else {
      ...
    }
  }
}
Share Improve this question edited Nov 26, 2016 at 22:37 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Nov 26, 2016 at 22:34 J. DoeJ. Doe 611 gold badge1 silver badge6 bronze badges 4
  • 3 Call it in ngOnInit or ngAfterViewInit? Have you read up on the lifecycle hooks? What have you tried? – jonrsharpe Commented Nov 26, 2016 at 22:35
  • @jonrsharpe I just tried to call it in ponent, but didn't work as it supposed to. I will check on google ngOnInit and will let u know bout the progress. – J. Doe Commented Nov 26, 2016 at 22:36
  • 2 angular.io/docs/ts/latest/guide/lifecycle-hooks.html – jonrsharpe Commented Nov 26, 2016 at 22:37
  • @jonrsharpe It works, thank u. – J. Doe Commented Nov 26, 2016 at 22:40
Add a ment  | 

2 Answers 2

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

}

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();
  }
发布评论

评论列表(0)

  1. 暂无评论