AngularJS with TypeScript

December 15th, 2017

Components

class HerosComponentController implements ng.IComponentController {
  public static $inject = ['$log', '$scope', '$document', '$element'];
  public title: string;
  public heros: IHero[];
  public onItemSelect: any;

  constructor(
    private $log: ng.ILogService,
    private $scope: ng.IScope,
    private $document: ng.IDocumentService,
    private $element: ng.IRootElementService,
  ) { }

  public $onInit () { }
  
  public $onChanges(changes: angular.IOnChangesObject): void { }
  
  public selectItem(item: IHero, event: any) {
    if (this.onItemSelect && typeof this.onItemSelect === 'function') {
      this.onItemSelect({
        data: item,
      });
    }
  }
}

class HerosComponent implements ng.IComponentOptions {

  public controller: ng.Injectable<ng.IControllerConstructor>;
  public controllerAs: string;
  public template: string;
  public bindings: any;

  constructor() {
    this.controller = HerosComponentController;
    this.controllerAs = "$ctrl";
    this.template = `
      <ul>
        <li>{{$ctrl.title}}</li>
        <li ng-click="$ctrl.selectItem(hero, $event)" ng-repeat="hero in $ctrl.heros">{{ hero.name }}</li>
      </ul>
    `;
    this.bindins = {
      title: '@',
      heros: '<',
      onItemSelect: '&',
    };
  }
}

angular
  .module("mySuperAwesomeApp", [])
  .component("heros", new HerosComponent());

angular.element(document).ready(function() {
  angular.bootstrap(document, ["mySuperAwesomeApp"]);
});
<heros title="Title" heros="$ctrl.heros" on-item-select="$ctrl.select(data)"></heros>