2016-11-26 17 views
1

私はウィンドウの幅をチェックする簡単な関数を持ち、その値に応じてコンテンツを伸ばします。しかし、ページのサイズを変更してサイトをリロードすると、ウィンドウのサイズを変更するまで何も起こりません。 angular2のページ読み込みで関数を呼び出すにはどうすればよいですか?ページの読み込み時に関数を実行するANGULAR 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私はちょうどそれをコンポーネントで呼び出そうとしましたが、想定どおりに動作しませんでした。私はGoogleの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、その後、あなたが負荷にangularjsからそのようなNG-のinitを呼び出したいngOnInit内部メソッドを呼び出します。

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

ngOnInit() { 
    this.checkScreenWidth(); 
    } 
関連する問題