Reputation: 863
I had written a calendar control in jQuery that I wanted to use in an Angular 2 project.
I've learned, from other answers on this topic, that I can use jQuery's getScript()
API to call into external JavaScript files.
My calendar.component.ts
looks like this:
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { Auth } from '../auth.service';
declare var $:any;
declare var CustomCal:any;
@Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css']
})
export class CalendarComponent implements OnInit {
private year : number;
myCal : any;
constructor(private auth : Auth) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.year = 2017;
$.getScript('./app/calendar/zapCalendar.js', function(){
console.log("got call'd back");
this.myCal = new CustomCal(2017);
});
}
}
I get the console message "got call'd back", then an error message stating that CustomCal
is not defined.
My CustomCal
class is defined in zapCalendar.js
as follows:
class CustomCal
{
constructor(nYear) {
this._mouseDown = false;
this._mouseDrag = false;
this._lastItem = 0;
this._nYear = nYear;
this.CreateCalendarFrame();
this.AddEventHandlers(this);
}
...
}
I've tried export'ing the class in the zapCalendar.js
file, and also tried adding the following to the zapCalendar.js
file:
$( function() {
var myCal = new CustomCal(2017);
});
What am I missing here?
Update:
I've just replaced this (in zapCalendar.js
):
$( function() {
var myCal = new CustomCal(2017);
});
with this:
var x = new CustomCal(2017);
And now the calendar is rendering correctly. But I'd like (if possible) to get a reference to the calendar in my typescript. Is this possible?
Upvotes: 0
Views: 1466
Reputation: 1
you need to export class then import it in your component
import {CustomCal} from "./app/calendar/zapCalendar";
Upvotes: 0
Reputation: 8610
$.getScript('./app/calendar/zapCalendar.js', function(){
console.log("got call'd back");
this.myCal = new CustomCal(2017);
});
The inner function here will not have the same this
reference because it won't be called bound to your object. Since you're using TypeScript, you can just use an arrow function to change this behavior.
$.getScript('./app/calendar/zapCalendar.js', () => {
console.log("got call'd back");
this.myCal = new CustomCal(2017);
});
Upvotes: 1