【发布时间】:2025-12-21 14:15:11
【问题描述】:
我正在尝试创建一些包装 Angular2 装饰器的功能。我想简化将 CSS 类添加到主机的过程,因此我创建了以下内容:
警告:不适用于 AOT 编译
type Constructor = {new(...args: any[]): {}};
export function AddCssClassToHost<T extends Constructor>(cssClass: string) {
return function (constructor: T) {
class Decorated extends constructor {
@HostBinding("class") cssClass = cssClass;
}
// Can't return an inline class, so we name it.
return Decorated;
};
}
我还希望能够创建另一个添加特定 CSS 类的装饰器。
/**
* Decorator to be used for components that are top level routes. Automatically adds the content-container class that is
* required so that the main content scrollbar plays nice with the header and the header won't scroll away.
*/
export function TopLevelRoutedComponent<T extends Constructor>(constructor: T) {
// This causes an error when called as a decorator
return AddCssClassToHost("content-container");
// Code below works, I'd like to avoid the duplication
// class Decorated extends constructor {
// @HostBinding("class") cssClass = "content-container";
// }
// return Decorated;
}
// Called like
@TopLevelRoutedComponent
@Component({
selector: "vcd-administration-navigation",
template: `
<div class="content-area">
<router-outlet></router-outlet>
</div>
<vcd-side-nav [navMenu]="navItems"></vcd-side-nav>`
})
export class AdminNavigationComponent {
navItems: NavItem[] = [{nameKey: "Multisite", routerLink: "multisite"}];
}
我得到的错误信息是
TS1238: Unable to resolve signature of class decorator when called as an expression. Type '(constructor: Constructor) => { new (...args: any[]): AddCssClassToHost<Constructor>.Decorated; p...' is not assignable to type 'typeof AdminNavigationComponent'. Type '(constructor: Constructor) => { new (...args: any[]): AddCssClassToHost<Constructor>.Decorated; p...' provides no match for the signature 'new (): AdminNavigationComponent'
我能够通过创建一个由两者调用的函数来解决它
function wrapWithHostBindingClass<T extends Constructor>(constructor: T, cssClass: string) {
class Decorated extends constructor {
@HostBinding("class") cssClass = cssClass;
}
return Decorated; // Can't return an inline decorated class, name it.
}
export function AddCssClassToHost(cssClass: string) {
return function(constructor) {
return wrapWithHostBindingClass(constructor, cssClass);
};
}
export function TopLevelRoutedComponent(constructor) {
return wrapWithHostBindingClass(constructor, "content-container");
}
有没有一种方法可以使第一种样式生效,而无需辅助函数或复制代码?我意识到我的尝试不是很好而且没有任何意义,但我无法理解错误消息。
与(某种)AOT 兼容的版本 因为下面要简单很多,所以不会导致 AOT 编译器崩溃。但是请注意,如果使用 webpack 编译器,自定义装饰器会被剥离,因此它仅在使用 ngc 编译时才有效。
export function TopLevelRoutedComponent(constructor: Function) {
const propertyKey = "cssClass";
const className = "content-container";
const descriptor = {
enumerable: false,
configurable: false,
writable: false,
value: className
};
HostBinding("class")(constructor.prototype, propertyKey, descriptor);
Object.defineProperty(constructor.prototype, propertyKey, descriptor);
}
【问题讨论】:
标签: typescript angular2-decorators