0

I have to do a workaround and initialize jQuery datetimepicker inside Angular 2 app (and it should be reworked later).

When I assign datetime value to a variable, it is not visible anywhere else in Angular app. Here is what I do:

datetime: string;

setDT() {
  jQuery(this.elementRef.nativeElement).find("#datetimepicker").datetimepicker({
    onChangeDateTime: function(currentDateTime) {
      this.datetime = currentDateTime;
      console.log(this.datetime); // -> logs correct selected datetime, i.e. Fri Mar 11 2016 10:00:00 GMT+0200 (EET)
    }
  });
}

but if I try to reach out this.datetime somewhere else it is undefined:

save() {
  console.log(this.datetime); // -> 'undefined'
}

How should be variables passed between jQuery and Angular 2?

Roman

3
  • Somewhere else means what? in same component or in some other component? Commented Mar 9, 2016 at 6:59
  • I mean same component Commented Mar 9, 2016 at 7:10
  • can you reproduce in plunker? Commented Mar 9, 2016 at 7:14

2 Answers 2

3

You will need to use jquery proxy to do that:

setDT() {
  jQuery(this.elementRef.nativeElement).find("#datetimepicker").datetimepicker({
    onChangeDateTime: jQuery.proxy(function(currentDateTime) {
      this.datetime = currentDateTime;
      console.log(this.datetime); // -> logs correct selected datetime, i.e. Fri Mar 11 2016 10:00:00 GMT+0200 (EET)
    }, this)
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Apparently, I was able to get needed value through

this.datetime = jQuery(this.elementRef.nativeElement).find("#datetimepicker").val();

but still would be great to receive an answer for educational reasons.

thanks again!

Comments

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.