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

TypeError: describe is not a function in the Mocha testing framework

Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined. TypeError: mocha_typescript_1.describe is not a function at DatabaseTest.WrongPath (test/database_test.ts:21:9) at Context.<anonymous> ...

Storing a child in an existing object with Firebase and Angular 6

How can I save a new form to an existing list with the following code snippet: createNewTumeur(newTumeur: Tumeur) { this.tumeurs.push(newTumeur); const id: string = this.route.snapshot.params['id']; firebase. ...

Having trouble getting errors to display on the Input onChange event with Antd

When using Antd, I am having trouble getting errors in the onChange event. Even when there is an error in a field, I cannot see the errors while typing in that particular field. For example; https://stackblitz.com/edit/react-qurm1n?file=demo.tsx Here are ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Employ ion-grid for a layout reminiscent of Duolingo's design

I am exploring the idea of creating a layout similar to Duolingo's interface. I have an array that specifies which buttons should be displayed, and I want them to be organized in pairs, with any odd element centered within the layout. However, I am s ...

The Next JS project fails to compile when a hyperlink is sent to the Link component from an external source

I am encountering an issue with a Menu Item component that pulls its href and label from another component known as NavBar. The strange thing is that it works perfectly fine when running yarn dev, but fails to build. However, when I make a simple change to ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

Unit testing in Angular 2+ involves testing a directive that has been provided with an injected window object

Currently, I am faced with the challenge of creating a test for a directive that requires a window object to be passed into its constructor. This is the code snippet for the directive: import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit ...

Advanced data synchronization with Angular 7's bidirectional data binding feature

One input box allows users to enter a number, and I would like to adjust the width of the background color based on that number. The box itself will have a fixed width, but I am looking to dynamically change the width of the background color according to ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

Retrieve a prepared response from a TypeORM query

I need to retrieve all the courses assigned to a user with a simple query: There are 2 Tables: students & courses return await this.studentsRepository .createQueryBuilder('s') .leftJoinAndSelect('courses', 'c' ...

How to implement a distinct click event for input elements containing a pipe character in Angular

I have developed an innovative Elevator application that features a unique elevator component displaying the current floor value in a box. You can see how it looks here: https://i.stack.imgur.com/h3JW5.png In order to replace the numerical floor values w ...

Adjusting the content of mat-cards to fill in blank spaces

I have encountered an issue with the alignment in a list using mat-card. Here is my current layout: https://i.stack.imgur.com/VKSw4.jpg Here is the desired layout: https://i.stack.imgur.com/8jsiX.jpg The problem arises when the size of content inside a ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...

Does Angular 4 Bundling Include the Complete Angular Library in the Bundle?

Is it possible that when running ng build --prod in CMD, Angular gathers all JavaScript files from node_modules and generates the vendor.bundle.js? To test this theory, I decided to delete certain definitions from package.json and rebuild. Surprisingly, t ...

What is the importance of context in the subscription method of RxJS or Angular Observables?

In the given situations, I am providing a child Component with a property that is updated later through an RxJs Observable subscription. Angular fails to detect changes when not using an anonymous function or binding the this context. // Situation 1 // C ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

Facing challenges with parsing JSON files in an Angular 2+ application

Utilizing the Angular CLI, I have configured this project with the standard folder layout. My goal is to practice reading a JSON file from src/app/assets/items.json and then using it to display these items in the HTML. items.json: { "results": [ ...