javascript - 在页面加载时执行函数,ANGULAR 2

标签 javascript angular

我有一个简单的功能,检查窗口的宽度并根据该值拉伸(stretch)内容。但是当我调整页面大小时并重新加载网站时,在我调整窗口大小时之前没有任何反应。如何在 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 {
      ...
    }
  }
}

最佳答案

您可以导入并实现angular2核心库的OnInit接口(interface),在类中实现该接口(interface)后定义其ngOnInit方法。我想它会完成这项工作。

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

}

关于javascript - 在页面加载时执行函数,ANGULAR 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40823824/

相关文章:

javascript - Angular 路由器可以公开父-当前-下一个路由吗?

javascript - 执行多个异步操作在所有操作完成时收到通知( typescript )

angular - OpenID 连接 : Implicit or Auth Code flow for SPAs?

javascript - .click 子div 但不触发单击parent Div?

javascript - 单击按钮时从服务器 NodeJS 请求数据

javascript - 使用 Workbox 预缓存 Firebase JS 文件 - 被 CORS 阻止

Angular2 RC : Added controls with addControls method after creation of the ControlGroup is not working

java - 如何使用PaymentIntent(Stripe)授权资金?

javascript - 为什么 angularjs ng-repeat 不能正常工作?

javascript - 防止图像而不是字符保存到数据库