0

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 ?

3 Answers 3

2

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); 
      }
      })
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes with arrow function that works ;) but I have mentioned it , how get the same result before => was out ?
that is because of a javascript concept called closures. In javascript each function is an object. before arrow in html 5 we had to use bind function. bind link
1

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()

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.