0

I keep running into issues with OnInit accessing functions within the same component class.

My basic setup is as follows:

import {Component, OnInit} from '@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 will fire the login function on page load as expected, but 2 complains login isn't a function. How do I appropriately access the login function within AppComponent?

1
  • 1
    You need to use an arrow function - document.onkeypress = (e)=> { ... } - to preserve the lexical scoping of this Commented Jul 25, 2016 at 21:48

1 Answer 1

2

This has to do with scoping. The time you call this.login from the onkeypress callback this refers to the global object so this.login is equal to window.login which in your case is undefined

Possible solutions

Cache this

var _this = this;
document.onkeypress = function(e){
    if ( document.body === document.activeElement ) {
        _this.login(); //2
    }

};

Explicitly set context with .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
    }

};
Sign up to request clarification or add additional context in comments.

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.