2

I think this should be fairly simple, but for the life of me I can't get it working.

I have an angular string (placeholder) that I would like to reference from a jQuery function that's fired on $document.ready(). Basically this is what I have:

placeholder: string;

ngOnInit() {
    this.translateService.get(['']).subscribe(translations => {
      this.placeholder = this.translateService.instant('placeholder');
      console.log('PLACEHOLDER', this.placeholder);  <<<<<<<<< has expected value
    });

    $(document).ready(function () {
      console.log('READY', this.placeholder);   <<<<<<<<< undefined
      $('#dropDown').select2({
        placeholder: this.placeholder,
        data: [
            ...
        ]
      });
    });        
}

How do I reference this.placeholder from within the jQuery function?

1
  • 1
    in document.ready this is refering to window object not to angular obj Commented Sep 30, 2019 at 6:49

2 Answers 2

4

When you use the function keyword, it defines its own this, which overrides the outer this you believed to use:

this.placeholder = 'Foo';
$(document).ready(function () {
  console.log('READY', this.placeholder); // this is another this, local to the function
}

There are two solutions:

With old JS

In pure JS you could just move away your outer this to use it inside:

this.placeholder = 'Foo';
var that = this;
$(document).ready(function () {
  console.log('READY', that.placeholder); // that refers to the outer this
}

With modern JS (ECMA script >5)

If you can use a modern browser with ECMA script >5, you can use the arrow function () => {} instead of function() {}, which automatically preserves the outer this:

this.placeholder = 'Foo';
$(document).ready(() => {
  console.log('READY', this.placeholder); // () => {} does not override this
}
Sign up to request clarification or add additional context in comments.

Comments

2

you can use something like below code. remove document.ready and function keyword

use arrow function to keep this in scope.

export class TestComponent implements OnInit {

placeholders:Array<string> = [];

constructor() { }

ngOnInit() {
  // removed function keyword and added () => {} syntax
  $('#btn').on('click', (e, arr) => {  
    console.log(this.placeholders);
  });
}

1 Comment

This solved the issue where I could not reach an angular service that had been passed in through the constructor from the jquery function. Simply removing the function keyword gave me access. Thank you!

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.