Angular 2 dependency injection in ES5 and ES6

To use Angular 2 with ES5 you need this script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.3/angular2-all.umd.js"></script>

This provides an global variable that contains all of Angular 2. Now you can write ng.core.Component instead of the @Component annotation. The first parameters of the Constructor are the injectables.

var Component = ng.core
  Component({
    selector: 'hello-cmp',
    template: 'Hello World!',
    viewProviders: [Service]
  .Class({
    constructor: [Service, function (service) { 
      ...
    }],
  });

And tell the injector that our service parameter is a instance of Service

Component.parameters = [[new ng.core.Inject(Service)]];

The following Exapmle shows the usage of angular2 with ES6:

import {Component} from 'angular2/core';
import {Service} from './example.service';

let componentAnnotation = new Component({
  selector: 'world-time',
  inputs: ['timeZones'],
  providers: [Service],
  template: `
    ...
  `
});
export class ComponentExample {
   constructor(service) {
    this._service = service;

   }
...

}

WorldTimeComponent.annotations = [componentAnnotation];
WorldTimeComponent.parameters = [[Service]];

In this plunkr you can find a working ES6 example.

But you can use decorators by using Babel. Enabling the optional[]=es7.decorators (in webpack) or by setting your configuration to stage:1.

Leave a Comment