0

I'm trying to figure out how to have a jquery function call a method in the enclosing Angular 2 Component.

I'm using the https://github.com/mdehoog/Semantic-UI-Calendar component in my Angular 2 project. I've declared a const of type any for jQuery, and then in my ngOnInit I do this:

   jQuery('#monthYearPicker').calendar({
        type: 'month',
        maxDate: new Date(),

        // minDate and maxDate take new Date() objects

        onChange: function(date, text, mode) {
            console.log("Date is " + date);
            console.log("Text is " + text);
        }
    });

I'm seeing the console log as expected. What I don't get now is how do I then call back into my component so that I can do 'normal' stuff at this point? For example, I now want to call my method that queries a webservice and pass in the date that was selected.

2 Answers 2

1

Use this.sampleFun() at your onChange event function. But first of all, you have to make a modify of your definition of anonymous function this way to keep the current context:

onChange: (date, text, mode) => {
    // console.log("Date is " + date);
    // console.log("Text is " + text);
    this.sampleFun();
}
Sign up to request clarification or add additional context in comments.

Comments

0

NOTE: if you are dealing with Jquery in angular2/typescript code, make sure you use jquery at ngViewAfterInit() life hook instead of ngOnInit()

fetcheData:any;

ngViewAfterInit(){

 jQuery('#monthYearPicker').calendar({
        type: 'month',
        maxDate: new Date(),

        // minDate and maxDate take new Date() objects

        onChange: (date, text, mode) => {             //used arrow function ()=>
            console.log("Date is " + date);
            console.log("Text is " + text);

            //call your webapi here on onChange event
            this.calltoWebapi();                      //calling a function
        }
    });
}

calltoWebapi(){
     //actual http call and get some response
     //this.fetchedData=response;
}

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.