Search code examples
javascriptjqueryangularangular5angular2-services

Cannot Access this from nested function in angular4


I have a component called abc and in that component I have three variable named title,Desc,Name and when I am trying to access it from nested function it gives me as undefined.

e.g.

@Component({
  selector: 'abc',
  templateUrl: './abc.component.html',
  styleUrls: ['./abc.component.css'],
  providers: [abcService]
})

export class abcComponent implements AfterViewInit,AfterViewChecked {

  title;
  Desc;
  Name;
  date=null;

test(){
this.title='a';
//work fine
}

test11(){

$('#cmg tbody').on('click', 'a.editor_edit', function (e) {
e.preventDefault();
this.title= false;  //gives me an undefined
});

}

}

Solution

  • This is because you are losing the scope in your callback. Modify it to use an arrow function so that you keep this

    $('#cmg tbody').on('click', 'a.editor_edit', (e) => {
      e.preventDefault();
      this.title= false;
    });
    

    Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.