Reputation: 3
I am learning new to create app in angular 4 , Now in one of my file
export class AppComponent {
str: string = "";
arr = [];
constructor(private elemRef: ElementRef, private rend: Renderer, private objComp: AppObjComponent) {
}
@HostListener('keyup', ['$event']) textKeyPressed(ev) {
console.log(this.elemRef);
if (ev) {
this.str = ev.target.value;
console.log(this.str);
this.objComp.obj.forEach(function(elem, index) {
if (elem.includes(this.str)) {
this.arr.push(this.str);
}
})
}
While compiling it compiles fine on the browser it throws error
AppComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'str' of undefined
Which is this line
if(elem.includes(this.str))
But if i print it using console.log it prints in the same function .
console.log(this.str);
I am not sure why it throws error for this.str it also throws error for this.arr if I comment this.str line. Not sure why it is not able to access the class variables .
Upvotes: 0
Views: 216
Reputation: 1162
You need to use an arrow function in the for each or bind the scope to the function (preferably the first option)
Upvotes: 0
Reputation: 14450
The this
in your forEach is not the this
of your class.
To retain the context of your class, either use a fat-arrow :
this.objComp.obj.forEach((elem, index) => {
if (elem.includes(this.str)) {
this.arr.push(this.str);
}
})
or use The thisArg
parameter of forEach (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) that tells :
If a thisArg parameter is provided to forEach(), it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
So :
this.objComp.obj.forEach(function(elem, index) {
if (elem.includes(this.str)) {
this.arr.push(this.str);
}
}, this ) // this added here
Upvotes: 1