How To Write Angular 1.5 Components with injected services in TypeScript

In this article I will briefly describe how to create an AngularJS 1.5 Component in TypeScript and how to inject services into this component.

Components are a good preparation if you plan to migrate to Angular 2.

service: SampleService.ts

Here we create the angular service and inject $q as dependency. The most important thing to note: the call to angular.module.service must be at the end of the file, because the typescript compiler transpiles the class to a variable without forward declaration. Placing the call at the top of the file will result in hard to debug error: “[ng:areq] Argument ‘fn’ is not a function, got undefined”.

Component: SampleComponent.ts

Here we create both the Component and ComponentController in one file. Here its also important to place the calls to angular.module at the end of the file. The bindings in the component constructor are almost equal to directive scope. For a complete list of options see https://docs.angularjs.org/guide/component . In facebook controller we inject the previously defined settings service.

Inside the template we can access the controller through the $ctrl variable.

Usage: some-other-component.html

Inside some other component or any html template we can use the new component like directives. Here we also pass a settingsObject.

Summary

That was my quick description how I set up an Angular 1.5 component in typescript. Its pretty simplified. Of course you need to run the typescript compiler and either concat the result or use a module loader.

I’m curious how you are creating components with angular 1.5 and typescript. Please comment if you have some suggestions.

Freelance Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store