2016-11-26 47 views
1

我有一個簡單的功能,檢查窗口的寬度,並根據該值拉伸的內容。但是,當我調整頁面大小並重新加載站點時,除非調整窗口大小,否則什麼都不會發生。如何在angular2中調用頁面加載函數?在頁面加載執行功能,角度2

我的整個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 { 
     ... 
    } 
    } 
} 
+3

在'ngOnInit'或'ngAfterViewInit'中調用它?您是否閱讀過生命週期掛鉤?你有什麼嘗試? – jonrsharpe

+0

@jonrsharpe我只是試圖在組件中調用它,但沒有按照預期的那樣工作。我會檢查谷歌ngOnInit,並讓你知道關於進展。 –

+2

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html – jonrsharpe

回答

3

您可以導入和實施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(); 
    } 

} 
0

從「@角/ core'module所有進口的OnInit首先,然後調用內部ngOnInit的方法要在負荷angularjs它像NG-初始化調用。

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

ngOnInit() { 
    this.checkScreenWidth(); 
    }