Reputation: 357
I am trying to push on an array for every interval but for some reason I get an error either it is ERROR TypeError: Cannot set property 'NaN' of undefined
if I use this.numbers[this.value] = this.value;
or it is core.es5.js:1020 ERROR TypeError: Cannot read property 'push' of undefined
if I use this.numbers.push(this.value);
here is my code
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.css']
})
export class GameControlComponent implements OnInit {
timer = null;
value: number;
interval: number;
numbers = [];
constructor() { }
ngOnInit() {
console.log(this.numbers);
}
onClickStart() {
console.log('timer called');
if (this.timer !== null) {
return;
}
this.timer = setInterval(function() {
this.value += 1;
// console.log(this.numbers[this.value - 1 ]);
// this.numbers[this.value] = this.value;
this.numbers.push(this.value);
console.log(this.numbers);
}, this.interval );
}
onClickStop() {
clearInterval(this.timer);
this.timer = null;
}
}
My html is
<div class="row">
<div class="col-xs-12 ">
<button type="submit" class="btn btn-success" (click)="onClickStart()">Start</button>
<button type="button" class="btn btn-danger" (click)="onClickStop()">Stop</button>
<button type="button" class="btn btn-primary" >Clear</button>
</div>
</div>
<div class="row">
<div class="col-xs-10">
<hr>
<ul class="list-group">
<a
class="list-group-item"
style="cursor: pointer"
*ngFor="let number of numbers"
>
<app-even [num]="number" ></app-even>
<app-odd [num]="number" ></app-odd>
</a>
</ul>
</div>
</div>
but I don't think it matters yet
Upvotes: 0
Views: 467
Reputation: 657416
function () {}
causes this
not to point to the current class instance anymore, as most coming from other languages would expect, use arrow functions instead to get the desired behavior:
this.timer = setInterval(() => {
Upvotes: 4