2017-04-10 48 views
0

我想弄清楚如何让jquery函数调用封闭Angular 2组件中的方法。我在Angular 2项目中使用了https://github.com/mdehoog/Semantic-UI-Calendar组件。我已经声明任何类型的jQuery的一个常量,然后在我的ngOnInit我这样做:jquery call angular 2组件方法

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); 
     } 
    }); 

我看到控制台日志预期。我现在没有得到的是,我怎样才能回到我的组件中,以便我可以在这一点上做'正常'的东西?例如,我现在想调用我的方法来查询web服务并传入选定的日期。

回答

0

注:如果您在angular2/typescript代码处理Jquery,使确保您使用的jQuery在ngViewAfterInit()生活挂钩,而不是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; 
} 
1

在您的onChange事件函数中使用this.sampleFun()。但首先,你必须让你的匿名函数的定义,这样的修改,以保持current context

onChange: (date, text, mode) => { 
    // console.log("Date is " + date); 
    // console.log("Text is " + text); 
    this.sampleFun(); 
}