是否可以在Typescript中装饰装饰器?

时间:2016-05-15 19:20:39

标签: typescript angular decorator

构建组件库,@ Component装饰器中有相当数量的样板文件。例如,样式和模板URL始终是相同的相对路径。想知道是否可以使用装饰器来干它。

我想我可以编写一个装饰器来复制@Component功能的那些部分,但我希望能够利用那些已经存在的东西。

1 个答案:

答案 0 :(得分:2)

你当然可以扩展组件功能并抽象一些功能, 以下是基于Extending component decorator with base class decorator

的解决方案

<强>组件metadata.ts

    import "reflect-metadata";
    import { ComponentMetadata } from "@angular/core";

    export function MyComponent(annotation: any): any {
      return function (target: Function) {
         let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
         let parentAnnotations = Reflect.getMetadata("annotations", parentTarget);

         let parentAnnotation = parentAnnotations[0];
         Object.keys(parentAnnotation).forEach(key => {
           if (isPresent(parentAnnotation[key])) {
              annotation[key] = parentAnnotation[key];
           }
        });

        let fileName: string = annotation.moduleId.substring(0, annotation.moduleId.lastIndexOf("."));
        annotation["templateUrl"] = fileName + ".html";
        annotation["styleUrls"] = [fileName + ".css"];        
        let metadata: ComponentMetadata = new ComponentMetadata(annotation);

        Reflect.defineMetadata("annotations", [metadata], target);
     }
   }

假设html和css与组件定义位于同一文件夹中并具有相同的名称,您可以根据需要进行更新。 例如,

html :some.component.html

css :some.component.css

<强> some.component.ts

   @MyComponent({
     selector: "some-component",
     moduleId: module.id 
   })
   export class SomeComponent{
      // Class implementation
   }

希望这会有所帮助!!

相关问题