Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - OnInit is not defined

I'm trying to implement the angular 2 onInit function but I get the following error in the console:

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

Can somebody point out what I'm doing wrong?

This is my component:

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

}
like image 899
Miha Šušteršič Avatar asked May 16 '16 15:05

Miha Šušteršič


1 Answers

Use single import instead of two import statements. Also use @ before @angular/core if you are using rc(release candidate) version

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

You should implement ngOnInit method as you component class implements OnInit class

ngOnInit() {
    this.checkOverflow();
}

Additionally don't use function in the way you are currently using in typescript file, do convert it to checkOverflow(){ ... } format & then call it like this.checkOverflow()

like image 94
Pankaj Parkar Avatar answered Sep 20 '22 14:09

Pankaj Parkar