2016-05-15 74 views
2

構建一個組件庫,並且在@Component裝飾器中有相當數量的樣板。例如樣式和模板網址總是相同的相對路徑。想知道是否可以使用裝飾器來烘乾它。是否可以在Typescript中修飾裝飾器?

我想我可以寫一個重複@Component功能的部分的裝飾器,但我希望能夠利用已經存在的部分。

回答

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 
    } 

希望這有助於!

+0

太棒了!感謝您的詳細示例。 – muaddoob