I have a jquery callback function in an angular 6 component. In that component there is a typescript variable. When a click event is triggered on the web page , the callback function will be called.But I want to send the typescript variable in the callback function too. How to do that?
export class A implements OnInit {
ngOnInit() {
this.initJquery();
}
private modalSelector = ''; // Typescript variable
initJquery() {
$(document).click(function(e) {
console.log(this.modalSelector);
});
}
}
But console.log(this.modalSelector)
; is printing undefined
You can achieve this using arrow functions.
In arrow functions, this
retains the value of the enclosing lexical context's this
. Read more here
initJquery() {
$(document).click((e) => {
console.log(this.modalSelector);
});
}