应用程序无法编译并出现错误
错误 NG6001:类
NavigationMenuItemComponent
列在 NgModule 的声明中AppModule
,但不是指令、组件或管道。要么从 NgModule 的声明中删除它,要么添加适当的 Angular 装饰器。
当我删除带有参数的构造函数时,错误消失了。在维护具有参数的构造函数的同时如何解决这个问题,因为我想用它来初始化组件列表,而不必为列表中的每个成员调用 set 方法
import {
Component,
OnInit
} from '@angular/core';
@Component({
selector: 'app-navigation-menu-item',
templateUrl: './navigation-menu-item.component.html',
styleUrls: ['./navigation-menu-item.component.scss']
})
export class NavigationMenuItemComponent implements OnInit {
static readonly ID_PREFIX: string = 'sidebar-menuitem-';
static readonly ICON_CLASS_PREFIX: string = 'mdi mdi-';
constructor(id: string, iconClass: string) {
this._id = NavigationMenuItemComponent.ID_PREFIX + id;
this._iconClass = NavigationMenuItemComponent.ICON_CLASS_PREFIX + iconClass;
}
//constructor() {}
private _id: string;
private _iconClass: string;
get id() {
return this._id;
}
get iconClass() {
return this._iconClass;
}
set id(id: string) {
this._id = NavigationMenuItemComponent.ID_PREFIX + id;
}
set iconClass(iconClass) {
this._iconClass = NavigationMenuItemComponent.ID_PREFIX + iconClass;
}
ngOnInit(): void {}
}
原文由 rnxfod 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想它正在发生,因为 Angular 旨在使用组件的构造函数与基于类而不是基元的依赖注入系统一起工作。
基本上,您 不能 创建自己的组件并为其构造函数提供所需的道具。
_为什么_,因为它会破坏控制反转原则,从而导致可维护性问题。
你可以做什么:
使用
@Input()
这个装饰器是 Angular 的开发团队专门设计的,用于在运行时为组件提供值。以后是否更改它们并不重要。你可以 在这里 和 这里 阅读更多如果您需要某种配置来全局或在某个级别提供,您可以创建自己的
Injector
并提供Token
您创建的组件可以使用。一些信息可以在 这里 找到基本上,您应该对第一种方法没问题,因为很清楚您在代码中做了什么,这是一种常见的做法,同时第二种方法更麻烦,更适合在服务中使用。
TL;博士
使用
@Input
因为这是将属性传递给子组件的常见做法。