首页 > 解决方案 > Angular - 如何在多个库中共享打字稿装饰器

问题描述

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

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);
    }
}

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

标签: angulartypescriptdecoratortypescript-decorator

解决方案


它是如此简单......但无处记录

我只是创建了另一个@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);
};
  • 由于某种原因,创建一个模块并在那里添加装饰器代码并从模块中导出不起作用

推荐阅读