Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input of object in template gives error "Property is used before its initialization" in Angular 10

I have a class:

import * as p5 from 'p5';

export class Snake{
    constructor() { }

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

I create its instance in app.component like this:

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

Then I input this instance via template of app.component into my component:

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

In component I try to use it like this:

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 { }
}

And I get an error Property 'snake' is used before its initialization. Any ideas on how to make it work?

like image 559
Mateusz Bugaj Avatar asked Feb 03 '23 14:02

Mateusz Bugaj


2 Answers

Move this line

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

to the ngOnInit() method. Right now you are calling this.snake on component initialization, but @Input was not yet passed to the component.

like image 176
Pawel Kiszka Avatar answered Feb 13 '23 06:02

Pawel Kiszka


NgOnInit is a lifecycle hook that is called after Angular has initialized all data-bound properties

Try assigning value to sketch in ngOnInit

 @Input() public snake: Snake;
 sketch;
  
 constructor() { }

 ngOnInit(): void {
     this.sketch = new p5(this.snake.sketch);
 }
like image 44
M A Salman Avatar answered Feb 13 '23 05:02

M A Salman