2

I'm running an Angular 1.5 project with TypeSCript and I'm running into some bugs. I want to check the scrollTop value from the .uc-card element.

public container = document.querySelector(".uc-card");

In my $onInit I have:

public $onInit() {
    this.scroll(this.container);
    this.doSomething();   
     
    this.container.addEventListener('scroll', function() {

        console.log('scrollOnInit');                
        this.scroll(this.container);
        this.doSomething();

    });
}

And I have 2 functions, scroll and doSomething:

private doSomething() {
    console.log('doSomething');
}

private scroll(e) {
    console.log('scroll')
    console.log(e.scrollTop);
    console.log(this.container.scrollTop);
}

When I run the application I get the following in the console log:

scroll
0
0
doSomething

This works fine. I returns the scrollTop value of my .uc-card element. But when I scroll I get the following:

scrollOnInit

CustomerActivitiesComponent.ts:38 Uncaught TypeError: this.doSomething is not a function HTMLDivElement. (CustomerActivitiesComponent.ts:38)

The scroll function does work since the output shows scrollOnInit. But the scroll function is not called (or at least does not show any ouput) and the doSomething method isn't a function. But they all work fine in the onInit.

1 Answer 1

2

Use an arrow function, =>. The regular function syntax does not keep the same this as the outside.

public $onInit() {
    this.scroll(this.container);
    this.doSomething();   
    // Setting event handler with arrow function guarantees `this` will be
    // the same as this it is here
    // It is like setting const _this = this, and using _this within the 
    // regular function
    this.container.addEventListener('scroll', () => {

        console.log('scrollOnInit');                
        this.scroll(this.container);
        this.doSomething();

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

1 Comment

Thanks Juan, haven't used the arrow functions before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.