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?
-
1in document.ready this is refering to window object not to angular objNegi Rox– Negi Rox2019年09月30日 06:49:31 +00:00Commented Sep 30, 2019 at 6:49
2 Answers 2
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
}
Comments
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);
});
}