簡體   English   中英

Angular2 - OnInit未定義

[英]Angular2 - OnInit is not defined

我正在嘗試實現angular 2 onInit函數,但我在控制台中收到以下錯誤:

錯誤:ReferenceError:未定義OnInit(...)

有人可以指出我做錯了什么嗎?

這是我的組成部分:

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();
    }

}

使用single導入而不是兩個import語句。 如果使用rc (候選版本)版本,也可以在@angular/core之前使用@

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

您應該在組件類implements OnInit類時實現ngOnInit方法

ngOnInit() {
    this.checkOverflow();
}

另外,不要以你當前在checkOverflow(){ ... }文件中使用的方式使用function ,將它轉換為checkOverflow(){ ... }格式然后像this.checkOverflow()一樣調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM