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?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With