0

I have a problem using Angular2. If I'm not mistaken in Angular2 I should put my code in class instead of controller and access variables by this but I have a variable I want to access from function assigned to window.onscroll, and this inside this function doesn't work, because it return window.

How can I access my variables or functions on scroll event?

class someClass{

    someVariable;

    ngOnInit() {
        this.someVariable = {}; 

        window.onscroll = function() {

            // here I want to access someVariable or someFunction

        }
    }

    someFunction() {
    }

}

1 Answer 1

4

I see several way to do that:

1) Using HostListener:

@HostListener('window:scroll') onScroll() {
  console.log(this.someVariable);
}

2) Using arrow function:

window.onscroll = _ => {
  console.log(this.someVariable);
};

3) Using of Function.prototype.bind():

window.onscroll = function() {
  console.log(this.someVariable);
}.bind(this);

4) Keep context in a variable like self or that:

let self = this;
window.onscroll = function() {
  console.log(self.someVariable); // <== notice self instead of this
};
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.