Encountering an error "Property is used before its initialization" in Angular 10 when attempting to input an object into a template

My code includes a class:

import * as p5 from 'p5';

export class Snake{
    constructor() { }

    sketch = (p: p5) => {
        p.setup = () => {
          ...
        }
    }
}

To instantiate this class in app.component, I do the following:

import { Component } from '@angular/core';
import { Snake } from './snake';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  snake = new Snake();
}

Next, I pass this instance to my component's template in app.component like so:

<game [snake]=snake ></game>

Within the component, I attempt to use it as shown below:

import { Component, OnInit, Input } from '@angular/core';
import { Snake } from '../snake';

@Component({
  selector: 'game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
  
  @Input()
  public snake: Snake;

  constructor() { }

  sketch = new p5(this.snake.sketch); // ERROR HERE

  ngOnInit(): void { }
}

However, when trying to execute the code, an error is thrown stating

Property 'snake' is used before its initialization.
I am seeking suggestions on how to resolve this issue. Thank you!

Answer №1

Relocate the following line

sketch = new p5(this.snake.sketch);

within the ngOnInit() function. Currently, you are invoking this.snake during component initialization, before @Input has been provided to the component.

Answer №2

The NgOnInit function is a crucial lifecycle hook in Angular that gets triggered once all data-bound properties have been initialized.

One way to utilize NgOnInit is by setting a value for sketch within the ngOnInit method.

 @Input() public cat: Cat;
 drawing;
  
 constructor() { }

 ngOnInit(): void {
     this.drawing = new p5(this.cat.drawing);
 }

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

The release of the Angular App within a webjar is causing problems relating to the baseHref

Currently, I am looking to package my Angular frontend in a webjar so that it can be easily imported via Maven into any Java backend. Successful in this task, I now have a Spring Boot backend with an application.properties file showing: server.servlet.cont ...

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

Utilizing Typescript within Visual Studio Code alongside node_modules

I currently have typescript installed and am utilizing the powerful visual code editor. Whenever I attempt to navigate to the definition of a typescript function in the node_modules directory, Visual Studio Code ends up expanding the entire 'node_mod ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

Transforming an object into an interface in TypeScript

Recently, I have started learning Typescript and am currently working on a project where I am building a REST API. In this project, I have defined a specific model for my request payload. However, even after typecasting, the type of 'resObj' rem ...

Utilizing observable services efficiently in Angular

I have developed a unique service for facilitating communication between various components and modules. @Injectable({ providedIn: 'root' }) export class CommunicationService<T> { private emitChanges = new Subject<T>(); changes ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

Issue: ENOENT - The file or directory 'google/protobuf/api.proto' does not exist

I am currently working on integrating Angular Universal into my project and I am utilizing the AngularFire library. However, when testing my application locally by running npm run build && npm run serve:ssr, I encountered the following error: webpack: ...

Encountering difficulties resolving the dependency tree for an angular-ionic project

Node version: v16.3.0 ng version: 12.1.0 Currently working on an Angular-Ionic 5 project Encountered an error while running the npm install command 2. Also tried running npm install --force but faced a different error ...

Is it possible to utilize useRef to transfer a reference of an element to a child component?

When I want to mount something into the element with id tgmlviewer, I call it a viewer object. This process works smoothly when there is only one component of this kind. import React, { useEffect } from "react"; import { Viewer } from "../.. ...

Manipulate and send back information from Observable in Angular

Here is an example of a scenario where I have created a service to retrieve a list of properties. Within this service, I am utilizing the map function to manipulate the response and then returning the final array as an Observable. My question is: How can ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

Having trouble uploading a file with Angular and Spring

The issue of uploading files to BE is causing me some trouble. I have been struggling to get it right, even with the code below: Angular service public saveFile(file: File): Observable<any> { const formData = new FormData(); formDat ...

Troubleshooting a MutationObserver issue in Angular Universal

I recently tried integrating Angular Universal with SSR into my current project. Even though I followed the provided tutorial, everything seemed to be working fine until I attempted to run the project. Upon executing npm run dev:ssr, I received a "Compil ...

Steps to reset Pipe in Angular 4

Is there a way to reinitialize a Pipe in Angular 4? I currently have a component that utilizes a Pipe. The component renders once with some data that uses the Pipe. If the data changes, the Pipe will also need to change. What is the best method to rein ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

The specified type 'x' cannot be assigned to the type 'x'. Error code: 2322

I encountered an issue with the code in @/components/ui/billboard.tsx file import { Billboard } from "@/types" interface BillboardProps { data: Billboard; }; const BillboardComponent: React.FC<BillboardProps> = ({ data }) => ...