0

I have variable called tableIndexNumber that i need use inside diffrent methodts. So when i try to reach that variable i use "this.tableIndexNumber" and i can reach it. But i cant use it this way inside Jquery each loop because of htmlElemets define as "this" too inside the each loop. So which way should i follow ?

export class TablesComponent implements OnInit {

tableIndexNumber = 1;

constructor() { }

change(col: number) {

$('#' + col).each(function () {

  if ($(this).attr('class') === 'box') {

    $(this).addClass('boxSelected');
    this.tableIndexNumber ++; 

  } else {
    $(this).removeClass('boxSelected').addClass('box');
  }
});

}

1

1 Answer 1

2

The old school way of handling this was to save this to a variable before the each called "context" or "that" or something like that, and then using that variable. Thankfully today we have arrow functions, which are perfect for this situation since they do not have their own this context.

UPDATE: I neglected to look up the syntax for each. Looks like you need the internal this, so an arrow function won't work. Instead, you can solve your problem by saving the outer this to a variable:

export class TablesComponent implements OnInit {
    tableIndexNumber = 1;

    constructor() { }

    change(col: number) {
        const component = this;
        $('#' + col).each(function() {
          if ($(this).attr('class') === 'box') {
            $(this).addClass('boxSelected');
            component.tableIndexNumber++; 
          } else {
            $(this).removeClass('boxSelected').addClass('box');
          }
        });
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey Zac. Firstly thank you so much for your answer. I ve tried your code but when i run that, it always goes to 'else' section. That way ($(this).attr doesnt work as correct way :/
My bad, I should have looked up the jQuery method first. I've updated my answer.
Thank you. By the is it possible to call that variable ("tableIndexNumber") inside html ?
HTML just handles general formatting. It doesn't know anything about variables or logic like JS. If you were using something like Angular or React, it would include a templating language that was an alternative to HTML, and you could insert logic into it. Without that, you'll need to use JS to insert the variable where you want it in the DOM.

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.