2016-05-15 6 views
2

コンポーネントライブラリをビルドすると、@Componentデコレータにかなりの定型文があります。たとえば、スタイルとテンプレートのURLは常に同じ相対パスです。デコレーターを使ってそれを乾燥させることが可能かどうか疑問に思う。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

関連する問題