Angular - 如何在多个库中共享一个打字稿装饰器

Angular - how to share a typescript decorator in several libraries

我使用以下装饰器为组件设置字符串“名称”:

ComponentRegistry.decorator.ts:

/* eslint-disable @typescript-eslint/no-explicit-any */
export const ComponentRegistry: Map<string, any> = new Map();

export const ComponentLookup = (key: string): any => {
  return (cls: any) => {
    ComponentRegistry.set(key, cls);
  };
};

我是这样使用它的:

profile-widget.component.ts:

import { Component } from '@angular/core';

import { ComponentLookup } from '../../../decorators/ComponentRegistry.decorator';

@ComponentLookup('ProfileWidgetComponent')
@Component({
  selector: 'dcd-fe-profile-widget',
  templateUrl: './profile-widget.component.html',
  styleUrls: ['./profile-widget.component.css']
})
export class ProfileWidgetComponent
{
}

所以我以后可以将它们动态加载到侧边导航菜单中:

...
  ngAfterViewInit(): void
  {
    // add all the (b4 menu) widgets into the sideNav
    for (let i = 0; i < this.config.widgets.b4.length; i++)
    {
      // get component class reference by it's name as a string
      const classRef = ComponentRegistry.get(this.config.widgets.b4[i]);  

      // add the defined widget to the b4MenuWidgets template
      this.addComponent(classRef, this.b4MenuWidgets);
    }
}

我想在几个库和应用程序本身中使用这个装饰器,而不复制代码,这可能吗?

原来如此简单... 尚无记录

我只是创建了另一个 @NgModule(称之为 'ui-util')

并将装饰器代码放在那里并将该模块导入我想使用装饰器的任何其他模块,如下所示:

ui-util.module.ts:

/* eslint-disable @typescript-eslint/no-explicit-any */
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
})
export class UiUtilModule {}


// implement decorators here ---- >

export const ComponentRegistry: Map<string, any> = new Map();

export const registerComponent = (key: string): any => {
  return (cls: any) => {
    ComponentRegistry.set(key, cls);
  };
};

export const findComponent = (key: string): any => {
  return ComponentRegistry.get(key);
};
  • 出于某种原因,创建模块并在其中添加装饰器代码并从模块导出无效