0

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 .

2
  • Try with: let that = this; this.objComp.obj.forEach(function(elem, index) { if (elem.includes(that.str)) { } }) and let me know Commented Jul 9, 2018 at 14:45
  • Although your answer is tecnically correct, in modern js thats not a good practice for this case, better to use an arrow function Commented Jul 9, 2018 at 14:55

2 Answers 2

1

The thisin 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 thisArgparameter 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
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use an arrow function in the for each or bind the scope to the function (preferably the first option)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.