Error: Undefined reference to OnInit in Angular 2

I'm currently working on implementing the angular 2 onInit feature, but I keep encountering an error in the console:

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

Could someone please help me identify what mistake I may be making?

Below is my component code for reference:

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

}

Answer â„–1

Optimize your import statements by using a single one instead of two separate ones. Remember to include @ before @angular/core if you are working with the rc (release candidate) version.

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

Ensure that you implement the ngOnInit method within your component class by having it implements OnInit.

ngOnInit() {
    this.checkOverflow();
}

Also, reconsider your use of function in your TypeScript file and convert it to the checkOverflow(){ ... } format. Then call it using this.checkOverflow()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...

Could this be a Typescript glitch? Getting the error "type not assignable" while trying to include a new property in an object

Dealing with two APIs that have contrasting property names for longitude coordinates—lon and lng, I am in the process of creating a converter function to accommodate both sets of data. This way, locations from either API can be used seamlessly. Encounte ...

Error: [X] does not behave like a function

I am utilizing angular4 along with dc.js to generate drill down charts. Here is the snippet of the code I am using: import { Component, ViewChild } from '@angular/core'; import { OnInit, AfterViewInit } from '@angular/core/src/metadata/lif ...

The access token generated by the Angular Keycloak adapter for Spring Boot backend authorization is not valid

The access tokens generated by Angular's keycloak adapter are invalid for communicating with a Spring Boot backend application secured by the same Keycloak realm. The localhost addresses were replaced with example.com to avoid issues with spam filters ...

What is the best way to incorporate Redux into your project?

Is it necessary to incorporate Redux for every API call, even when the data is not shared among multiple components? For instance, consider a users-list component that needs to fetch and display the list of users exclusively within its own interface. Is ...

Achieve a main-menu container with a full width dropdown using Bootstrap 4

I want the dropdown to start from the initial position for all menus and maintain a width of 600px. Even if I attempt to open the dropdown for "Main Menu 2" or "Main Menu 3" or "Main Menu 4", the dropdown should always start from the position of "Main Men ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...

What is the most effective approach for handling user input delays with Async promises?

New to Vue.js and currently exploring the following challenge: I have a component named PopUp which can be displayed or hidden using functions of the same name. My goal is for the popUp.show() function to return a promise that contains information about ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Typescript: Establishing a class method with parameters that are inherent to the class

After creating a class, I realized that there is repeated logic that can be extracted into a method on the class to be reused by other properties of the class. class Card { protected readonly data: Data; protected readonly user: User; nameVal: strin ...

Encountering difficulties upgrading to Angular 8 as the necessary command cannot be located

Looking to enhance my ionic application, I embarked on the journey of upgrading. Initially, I attempted using ng update However, it was met with an error message saying bash: ng: command not found Determined to make progress, I then turned to np ...

What is the process of declaring a global function in TypeScript?

I am looking to create a universal function that can be accessed globally without needing to import the module each time it is used. The purpose of this function is to serve as an alternative to the safe navigation operator (?) found in C#. I want to avoi ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Match a unique key in Typescript to ensure the same value for two distinct generic objects

There is a peculiar occurrence in TypeScript that I cannot comprehend. The desired outcome is to have a function structured like this: function getDbRowFromRow<T, Key extends keyof T, R extends Pick<T, Key>>( dbRow: T[], key: Key, row: R ...

Utilizing a personalized URL path in Spring Boot and Maven for backend responses leads to a whitelabel error

I am currently working on two separate projects, one being a projectApi (backend developed in Spring) and the other a projectUi (frontend developed in Angular). To combine these two projects into a single jar for production, I am using the maven-resource-p ...

We are unable to update the document in AngularFire as the document reference ID could not be retrieved

I am currently working on an update function that is designed to retrieve a specific document based on its unique document uid, which is connected to the authenticated user's uid. In another part of my code, I have a function that successfully fetche ...

Angular syncfusion - How can I retrieve the selected series in a line chart event?

Currently, I am using the Line chart control from Syncfusion in Angular 7. While going through the documentation, I was unable to locate an event that retrieves the selected data series when clicking on a line chart series. Do you happen to know the name o ...

Unable to determine the type of reference being used in the useInView function in TypeScript

import React from "react"; import { useInView } from "react-intersection-observer"; type PictureProps = { title: string; imageURL: string; }; export default function Picture({ title, imageURL }: PictureProps) { const { ref ...

Stopping an ongoing API service call when an Angular route changes can be achieved by following these steps

Within my application, there are various pages accessible through the dashboard. When loading the dashboard page, multiple API services are called to retrieve reports. However, if a user clicks on a different page link while the dashboard is still loading, ...

What causes the headers object to become empty when Angular processes an HTTP error?

Whenever my API (.Net Core) sends a response, it includes a correlation id header to track each interaction uniquely. This process is managed at the beginning and end of the pipeline to ensure accurate identification. If there's an exception in my app ...