是否可以在Typescript中修饰装饰器?
问题描述:
构建一个组件库,并且在@Component装饰器中有相当数量的样板。例如样式和模板网址总是相同的相对路径。想知道是否可以使用装饰器来烘干它。是否可以在Typescript中修饰装饰器?
我想我可以写一个重复@Component功能的部分的装饰器,但我希望能够利用已经存在的部分。
答
你当然可以延长部件的功能和抽象的某些功能, 下面是基于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
}
希望这有助于!
太棒了!感谢您的详细示例。 – muaddoob