Reputation: 125
The basketList objest is available in the html and in the Life Cycle Hook ngOnInit. However, when I try to access it with a function this.set() defined outside the hook then it doesn't work.
export class MenuOrderItemComponent implements OnInit, OnChanges {
@Input() basketList: any;
set(): void{
setInterval(function(){
console.log(this.basketList);
console.log(this.basketList.length);
},3000);
}
constructor() { }
ngOnInit() {
console.log('item');
console.log(this.basketList);
console.log(this.basketList.length);
this.set();
}
I'm getting undefined for this.basketList and the error TypeError: Cannot read property 'length' of undefined
for the second console.log in this.set()
Upvotes: 0
Views: 62
Reputation: 3520
The issue is that function() {}
defines a new this
object, so by using this
inside it you're actually acessing a different this
object, not the MenuOrderItemComponent
's one (and this other this
object does not have a basketList
property).
To solve this, you may use an arrow function, which does not have its own this
, which means that it will use the parent's this
(as you're expecting):
setInterval(() => {
console.log(this.basketList);
console.log(this.basketList.length);
},3000);
For more info, check the Arrow functions section here
Upvotes: 1
Reputation: 131
You will get the updated value of 'basketList'
in ngOnchange()
life cycle hook-
@input() id: number;
@input() name: string;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
// Output
{id: SimpleChange, name: SimpleChange}
And by setter method of typescript-
@Input() set basketList(data: any) {
// you might do something special in here
this.basketList= data;
}
Upvotes: 1
Reputation: 8558
It seems that the issue is about scope. You can either use arrow function
or bind
the scope manually.
export class MenuOrderItemComponent implements OnInit, OnChanges {
@Input() basketList: any;
set = (): void => {
// ^^^^^^^^^ Here
setInterval(() => {
// ^^^^^^^^^ And here
...
},3000);
}
......
Upvotes: 1