ikramf90
ikramf90

Reputation: 112

Scoping "this" in angular and Jquery

In my angular-7 class, I am using jquery, I want to store all text from h4 tags in an array. But when I use this it only refers to angular's this and not jquery's this. I tried using the fat arrow as well but it didn't work for me.

I tried using callback parameters to access elements, but they stay undefined.

Here's my code. any suggestions/help is appreciated.

thanks.

$('h4').each((idx, elem) => {
            this.listItems.push({ id: idx, text: elem.innerText });
        });

Upvotes: 1

Views: 51

Answers (2)

Abdul Basit
Abdul Basit

Reputation: 1382

This might help you

var that = this;
    $('h4').each(function (idx, elem) {
                //use that for angular component's this
                that.listItems.push({ id: idx, text: elem.innerText });
     });

Upvotes: 0

Ved_Code_it
Ved_Code_it

Reputation: 774

arrow function do not create its own scope (this) use normal function if you want to create function scope like this

var that=this;
    $('h4').each(function (idx, elem) {
                //use that for angular component's this
                this.listItems.push({ id: idx, text: elem.innerText });
            });

Upvotes: 2

Related Questions