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 .
let that = this; this.objComp.obj.forEach(function(elem, index) { if (elem.includes(that.str)) { } })and let me know