Javascript 在页面加载上执行函数,角度2

Javascript 在页面加载上执行函数,角度2,javascript,angular,Javascript,Angular,我有一个简单的函数,检查窗口的宽度,并根据该值拉伸内容。但是,当我调整页面大小并重新加载站点时,在调整窗口大小之前不会发生任何事情。如何在angular2中调用页面加载函数 我的整个app.component.ts文件: import { Component } from '@angular/core'; @Component({ templateUrl: './app.component.html' }) export class appComponent { private ch

我有一个简单的函数,检查窗口的宽度,并根据该值拉伸内容。但是,当我调整页面大小并重新加载站点时,在调整窗口大小之前不会发生任何事情。如何在angular2中调用页面加载函数

我的整个
app.component.ts
文件:

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 {
      ...
    }
  }
}
从'@angular/core'导入{Component};
@组成部分({
templateUrl:“./app.component.html”
})
导出类appComponent{
私有checkScreenWidth(){
如果(window.innerWidth<1000&&window.innerWidth>499){
...
}否则如果(窗内宽度<500){
...
}否则{
...
}
}
}

在类中实现接口后,您可以导入并实现angular2核心库的
OnInit
接口,并定义其
ngOnInit
方法。我想它会成功的

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

}
导出类appComponent实现OnInit{
私有checkScreenWidth(){
如果(window.innerWidth<1000&&window.innerWidth>499){
...
}否则如果(窗内宽度<500){
...
}否则{
...
}
}
恩戈尼尼特(){
这是checkScreenWidth();
}
}

首先从“@angular/core”模块导入OnInit,然后调用ngOnInit中的一个方法,您希望在加载时调用它,就像从angularjs调用ng init一样

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

 ngOnInit() {
    this.checkScreenWidth();
  }

ngOnInit
ngAfterViewInit
中调用它?你读过生命周期挂钩吗?你们试过什么?@jornsharpe我只是试着在组件中调用它,但并没有按照它的预期工作。我会检查google ngOnInit并让你知道进展情况。@jornsharpe它可以工作,谢谢你。在页面运行init函数loads@DhireshBudhiraja这就是他所需要的:“如何在angular2中调用页面加载函数?”阅读问题。你的否决票是不公平的!