2016-05-16 49 views
9

我想實現的角2的OnInit功能,但我得到以下錯誤在控制檯:Angular2 - OnInit中沒有定義

Error: ReferenceError: OnInit is not defined(...)

有人能指出我在做什麼錯?

這是我的組件:

import { Component, OnInit } from 'angular2/core'; 
import { ViewEncapsulation } from 'angular2/core'; 

@Component({ 
    selector: 'Landing', 
    templateUrl: '/app/views/landing.html', 
    styleUrls: ['../app/styles/landing.css'], 
    encapsulation: ViewEncapsulation.None 
}) 

export class LandingComponent implements OnInit { 

    function checkOverflow() { 
     var element = document.querySelector('.appContainer'); 
     if((element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){ 
      // your element have overflow 
      console.log('OVERFLOW!'); 
     } 
     else{ 
      console.log('NO OVERFLOW'); 
     } 
    } 

    OnInit() { 
     checkOverflow(); 
    } 

} 

回答

13

使用single進口,而不是兩個import語句。 @angular/core之前也使用@如果你正在使用rc(發佈候選)版

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

你應該實現ngOnInit方法,您組件類implements OnInit

ngOnInit() { 
    this.checkOverflow(); 
} 

另外不要在方式使用function你目前正在使用打字稿文件,請將其轉換爲checkOverflow(){ ... }格式&然後稱其爲this.checkOverflow()

相關問題