Hamza Haddad
Hamza Haddad

Reputation: 1556

using this keyword in angular in nested functions

Hi I would know how can I use variables of the component in nested function.

Here's an example:

export class AppComponent implements OnInit {
  name = ['Angular 6','Angular5','Angular4','Angular2'];
  isexist: string[]=[];

ifExist(text){
  var that= this;
  console.log("first ",this);
  var test="test";
  let exist= this.name.map(function (elm){
    if(elm==text) {
      console.log(this);
      this.isexist.push(elm); // works with that.isexist.push(elm); 
      }
      })
}
ngOnInit() {
  this.ifExist('Angular 6');

}

Here's what I get in browser dev tool

first  AppComponent {name: Array(4), namev: "helo", isexist: Array(1)};
second undefined

I have some questions How can I access to isexist without using arrow funtion ? why the second this does not contain test element ?

Upvotes: 0

Views: 3363

Answers (3)

Omer Gurarslan
Omer Gurarslan

Reputation: 1027

The reason why you cannot access to ifExists without using arrow functions is that this in an arrow function has the same value as the context in which the arrow function was created.

this in a normal anonymous function however, has the value of the context in which the normal function was called from ( In your case, the context and scope of normal function is only the inside of ifExists method.

Upvotes: 1

baao
baao

Reputation: 73251

There's no reason at all to loop, as you're only checking if an array contains an element. You don't even return from map(). The other answers already explain your problem with this, and here's how you should refactor your code (rewrote to plain js to make it work in the snippet, but you get the idea):

class Foo {
  constructor() {
     this.name = ['Angular 6','Angular5','Angular4','Angular2'];
     this.isexist = [];
  }
  
  ifExist(text) {
    if (this.name.includes(text)) this.isexist.push(text);
  }
  
  runner() {
    this.ifExist('Angular 6');
    console.log(this.isexist);
  }
}


new Foo().runner()

Upvotes: 1

Achu
Achu

Reputation: 272

try lambda here:

ifExist(text){
  var that= this;
  console.log("first ",this);
  var test="test";
  let exist= this.name.map((elm)=>{
    if(elm==text) {
      console.log(this);
      this.isexist.push(elm); // works with that.isexist.push(elm); 
      }
      })
}

Upvotes: 2

Related Questions