What is best practice to create an AngularJS 1.5 component in Typescript?

前端 未结 7 1697
北荒
北荒 2021-01-30 02:20

I am experimenting with the .component() syntax in Angular 1.5.

It seems that the latest fashion is to code the controller in-line in the component rather t

7条回答
  •  悲&欢浪女
    2021-01-30 02:53

    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: `
        
    {{ct}}
    ` }) 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

提交回复
热议问题