【问题标题】:Angular2 - OnInit is not definedAngular2 - OnInit 未定义
【发布时间】:2016-09-12 10:27:01
【问题描述】:

我正在尝试实现 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();
    }

}

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    使用single import 而不是两个 import 语句。如果您使用的是rc(候选发布版)版本,请在@angular/core 之前使用@

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

    您应该在组件类implements OnInit 类中实现ngOnInit 方法

    ngOnInit() {
        this.checkOverflow();
    }
    

    另外,不要以您当前在 typescript 文件中使用的方式使用 function,请将其转换为 checkOverflow(){ ... } 格式,然后像 this.checkOverflow() 一样调用它

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 2018-08-15
      • 2016-08-21
      • 1970-01-01
      • 2016-03-27
      • 2017-12-29
      • 2017-07-16
      • 1970-01-01
      相关资源
      最近更新 更多