What is best practice to create an AngularJS 1.5 component in Typescript?
If you wanted to completely adopt an Angular 2 approach, you could use:
module.ts
import { MyComponent } from './MyComponent';angular.module('myModule', []) .component('myComponent', MyComponent);
MyComponent.ts
import { Component } from './decorators';@Component({ bindings: { prop: '<' }, template: '<p>{{$ctrl.prop}}</p>'})export class MyComponent { prop: string; constructor(private $q: ng.IQService) {} $onInit() { // do something with this.prop or this.$q upon initialization }}
decorators.ts
/// <reference path="../typings/angularjs/angular.d.ts" />export const Component = (options: ng.IComponentOptions) => { return controller => angular.extend(options, { controller });};
I am using a simple Typescript decorator to create the component
function Component(moduleOrName: string | ng.IModule, selector: string, options: { controllerAs?: string, template?: string, templateUrl?: string}) { return (controller: Function) => { var module = typeof moduleOrName === "string" ? angular.module(moduleOrName) : moduleOrName; module.component(selector, angular.extend(options, { controller: controller })); }}
so I can use it like this
@Component(app, 'testComponent', { controllerAs: 'ct', template: ` <pre>{{ct}}</pre> <div> <input type="text" ng-model="ct.count"> <button type="button" ng-click="ct.decrement();">-</button> <button type="button" ng-click="ct.increment();">+</button> </div> `})class CounterTest { count = 0; increment() { this.count++; } decrement() { this.count--; }}
You can try a working jsbin here http://jsbin.com/jipacoxeki/edit?html,js,output
This is the pattern I use:
ZippyComponent.ts
import {ZippyController} from './ZippyController';export class ZippyComponent implements ng.IComponentOptions { public bindings: { bungle: '<', george: '<' }; public transclude: boolean = false; public controller: Function = ZippyController; public controllerAs: string = 'vm'; public template: string = require('./Zippy.html');}
ZippyController.ts
export class ZippyController { bungle: string; george: Array<number>; static $inject = ['$timeout']; constructor (private $timeout: ng.ITimeoutService) { }}
Zippy.html
<div class="zippy"> {{vm.bungle}} <span ng-repeat="item in vm.george">{{item}}</span></div>
main.ts
import {ZippyComponent} from './components/Zippy/ZippyComponent';angular.module('my.app', []) .component('myZippy', new ZippyComponent());