Bootstrapping an Angular 1.5 Component with Typescript

Angular 1.5 introduces the “Component” concept in order to get closer to Angular 2. By now you might have started to use typescript in your project, but upgrading to Angular 2 was too big of a step. However, you can start writing “Components” in an exact-angular2-style. Here’s what you’ve got to do.

First of all you’re going to need the following code to make annotations work:

//component.ts
function Component(moduleOrName: string | ng.IModule, selector: string, options: {
  controllerAs?: string,
  template?: string,
  templateUrl?: string,
  bindings?: any
}) {
  return (controller: Function) => {
    var module = typeof moduleOrName === "string"
        ? angular.module(moduleOrName)
        : moduleOrName;
    module.component(selector, angular.extend(options, { controller: controller }));
  }
}

This will allow you to use annotations to define components.

A ready-to-use component can then be generated with the following scripts:

#creates skeletton
#argument: name in any case e.g. bla-bla or blaBla or BlaBla

pascalcase="$(node changecase.js ${1} pascalCase)"
paramcase="$(node changecase.js ${1} paramCase)"
camelcase="$(node changecase.js ${1} camelCase)"

mkdir WebContent/components/directives/${paramcase}

echo "
@Component('taskbaseApp', '${camelcase}', {
  templateUrl: '/components/directives/${paramcase}/${paramcase}-directive.html',
  bindings: {
    somebinding: \"<\" // One Way Binding
  }
})
class ${pascalcase} {

  public somebinding: string;
  static \$inject: string[] = ['Utils'];

  constructor(private Utils) {}

  public sayHello() {
    console.log('hi')
  }

}
" >> WebContent/components/directives/${paramcase}/${paramcase}-directive.ts


echo "<div class='${paramcase}-wrapper'>

  <button class=\"btn btn-default\" ng-click=\"\$ctrl.sayHello()\">Hello {{\$ctrl.somebinding}}</button>

</div>" >> WebContent/components/directives/${paramcase}/${paramcase}-directive.html


# Compile
cd WebContent/components && tsc

echo "Usage:

<${paramcase} somebinding=\"'World'\" ></${paramcase}>

"

and

//changecase.js
var changeCase = require('change-case');

var caseType = process.argv[3];
var inpt = process.argv[2];
console.log(changeCase[caseType](inpt));

Note: You need to `npm install changecase –save` in order for the scripts to run first.

That’s all.

Leave a Reply

Your email address will not be published.