Passing javascript global variable to Angular2 (Typescript)


This content refers to angular2 version 2.0.0-beta.8. If it does not work for you probably because of breaking change in the future updates.

There are a couple ways to do this but I would basically mention only 2 approach.

The first approach, simply add declare var in component that you need to use.

In javascript code, declare variable in global scope:

var func = function() { … }

In Angular2, in the component that need to refer to javascript variable simply declare the same variable with the same name.

declare var func:Function;

This is the easiest way to archive the need but not the most efficient way. It looks like to be a magic variable in the component and is a great enemy of unit testing.

Since dependency injection (DI) pattern is one of the core concept of the  Angular2 (and AngularJS) and we should comply that 🙂

The second approach, import and inject from javascript to Angular2.

In javascript code, declare variable in global scope:

var func = function() { … }

at import statement which normally in the main html page. Passing func variable to the main function of main module.

System.import(‘app/main’)
.then((module) => module.main(func));

Update main.ts TypeScript file. Wrap Angular2 bootstrap with a main function which accept a parameter from import statement above. Inject func variable using provide feature.

import {provide} from ‘angular2/core’;

…….

export function main(func) {
bootstrap(AppComponent, [
//…providers and services
provide(‘func’, { useValue: func})
]);
}

In AppComponent that bootstrap from main.ts, inject func variable to constructor and use as needed. For more information about @Inject decorator please refer to this screencast tutorial – https://egghead.io/lessons/angular-2-using-the-inject-decorator.

export class AppComponent {
constructor(@Inject(‘func’) func:Function) {
// use func variable as needed
}
}

Now you have access to javascript variable and retain dependency injection concept and of course no magic variable!

 

 

Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: