angular - 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);
}
}
我想在几个库和应用程序本身中使用这个装饰器,而不复制代码,这可能吗?
解决方案
它是如此简单......但无处记录
我只是创建了另一个@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);
};
- 由于某种原因,创建一个模块并在那里添加装饰器代码并从模块中导出不起作用
推荐阅读
- javascript - 如何使用javascript从字符串传递到对象?
- sql - 使用 Athena 的 presto sql 创建时,是否可以在表名中包含执行月份?
- javascript - 我无法使用 onreadystatechange 方法触发 XMLHttpRequest 是更好的使用方法
- amazon-web-services - 无法通过 Bitbucket Pipeline 的 OIDC 连接在 AWS 上获取“分支名称”
- mysql - 对列进行 api 调用时,如何从同一个表的另一列侧加载某些内容?
- r - 根据从一列到新一列的行重新打印所有其他值
- ios - 在 UIStackView 中自动配置组件(以编程方式)
- powershell - 查找进程和服务并将它们与 powershell 中这些服务的基本版本进行比较
- java - 如何将数字签名应用于我的代码
- javascript - 在 Javascript 中使用和保存或优化这些变量的最佳方法是什么