Ad

ES6 Equivalent Of This Angular 2 Typescript

I have this typescript and I want to write the ES6 equivalent. I'm learning angular 2 and would prefer to use ES6 over typescript, and all the samples are in either ES5 or typescript. If I see how this code is written in ES6 then I should be able to take it from there with any new code I need to write based off of typescript. Cheers.

'use strict';
import {Component, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app',
  template: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyApp {
  constructor() {
    this.name = 'Max';
  }
}
Ad

Answer

ES6 equivalent of your code is in this plunk. I've changed your code a little bit by adding a service to demonstrate a parameters property (see below).

Explanation

I think you don't know how to convert decorators and types into ES6.

  1. To replace class decorators (such as Component and Directive) add annotation property to a component . You can use static getter for this:

    class App {
    
      static get annotations() {
        return [
          new Component({
            selector: 'my-app',
            template: '<h1>Hello, {{ name }}</h1>',
            providers: [Service]
          })
        ];  
      }
    
      // ...
    }
    
    // or just add `annotation` after class declaration
    App.annotations = [
      new Component({
        selector: 'my-app',
        // ...
      })
    ];
    
  2. To replace parameter decorators (such as @Inject) and types (constructor(type: Type)) add parameters property to a component. Again you can use static getter for this:

    class App {
      // ...
    
      static get parameters() {
        return [[Service]];
      }
    
      constructor(service) {
        this.name = service.getName();
        setTimeout(() => this.name = 'Max', 1000);
      }
    }
    
    // or just add `parameters` after class declaration
    App.parameters = [[Service]];
    
Ad
source: stackoverflow.com
Ad