javascript - Angular2 - OnInit accessing functions -
i keep running issues oninit accessing functions within same component class.
my basic setup follows:
import {component, oninit} '@angular/core'; ... export class appcomponent implements oninit { login(){...} ngoninit() { this.login(); //1 document.onkeypress = function(e){ if ( document.body === document.activeelement ) { this.login(); //2 } };
1 fire login function on page load expected, 2 complains login isn't function. how appropriately access login function within appcomponent?
this has scoping. time call this.login
onkeypress
callback this
refers global object this.login
equal window.login
in case undefined
possible solutions
cache this
var _this = this; document.onkeypress = function(e){ if ( document.body === document.activeelement ) { _this.login(); //2 } };
explicitly set context .bind
document.onkeypress = function(e){ if ( document.body === document.activeelement ) { this.login(); //2 } }.bind(this);
use es6 arrow functions ()=>{}
document.onkeypress = (e) => { if ( document.body === document.activeelement ) { this.login(); //2 } };
Comments
Post a Comment