![](/img/trans.png)
[英]Q: Angular components broken - "Class is using Angular features but is not decorated. Please add an explicit Angular decorator"
[英]Class is using Angular features but is not decorated. Please add an explicit Angular decorator
我有一些组件,如CricketComponent
、 FootballComponent
、 TennisComponent
等。所有这些类都有一些共同的属性:- TeamName, teamSize, players
等,它们是@Input()
。
现在我创建了一个BaseComponent
类,在其中定义了所有这些属性,这个baseComponent
类将由 cricket/football/tennis/etcComponents 扩展。
基础组件.ts
export class BaseComponent {
@Input() TeamName: string;
@Input() teamSize: number;
@Input() players: any;
}
板球组件.ts
@Component({
selector: 'app-cricket',
templateUrl: './cricket.component.html',
styleUrls: ['./cricket.component.scss']
})
export class cricketComponent extends BaseComponent implements OnInit {
constructor() {
super();
}
ngOnInit(): void {
}
}
我收到此错误:
src/app/base-screen.ts:4:14 中的错误 - 错误 NG2007:
类使用 Angular 特性但没有修饰。 请添加一个明确的 Angular 装饰器。
您需要将@Component
装饰器添加到该基础 class (可能也应该声明为abstract
)。
这是您在 Angular 9 中可以摆脱的最低限度:
@Component({
template: ''
})
export abstract class BaseComponent {
@Input() teamName: string;
@Input() teamSize: number;
@Input() players: any;
}
对于 Angular 10+,请参阅此答案。
从 Angular 10 开始,您可以通过将装饰器 @Injectable() 添加到抽象基础 class 来解决此问题,如下所示:
@Injectable()
export abstract class BaseComponent {
@Input() teamName: string;
@Input() teamSize: number;
@Input() players: any;
}
虽然在使用@Component
时接受的答案是正确的,但一个小缺点是它要求所有构造函数参数类型都可以由 DI 解析。 因此,如果您的基本 class 构造函数采用常量/文字(例如枚举)作为标志,您将不得不设置相应的 DI 提供程序/令牌才能使其编译。
但是,您也可以使用@Directive
装饰器来解决 NG2007,这不需要 DI 兼容性
看一下:缺少 @Directive()/@Component() 装饰器迁移
前:
export class BaseComponent {
@Input() TeamName: string;
@Input() teamSize: number;
@Input() players: any;
}
之后:
@Directive()
export class BaseComponent {
@Input() TeamName: string;
@Input() teamSize: number;
@Input() players: any;
}
如果您在 Angular 15 中遇到此问题,请使用准确版本的 TypeScript。 4.8.2 对我有用。
npm i typescript@4.8.2 -D --save-exact
我在运行ng serve
时遇到了类似的情况。 对于第 3 方库和我的所有 Angular 组件,即使它们已被装饰,我也遇到了该错误。
如果您遇到此问题,请参阅Angular 11 'error NG2007: Class is using Angular features but is not decorated 的答案。 但是 class 是装饰的
对于这些错误:NG6001:类“XComponent”列在 NgModule“AppModule”的声明中,但不是指令、组件或管道。 要么将它从 NgModule 的声明中移除,要么添加一个合适的 Angular 装饰器。
NG2003:类“Y”的参数“A”没有合适的注入标记。
NG2007:类正在使用 Angular 功能但未修饰。 请添加一个明确的 Angular 装饰器。
您可能正在 @Component 声明和 Component 类之间编写新类。
前任。
// 导出类 Y{ // }
@Component({
selector: 'app-X',
templateUrl: './X.component.html',
styleUrls: ['./X.component.css']
})
export class XComponent implements OnInit {
todos : Y[] = [
new Y(1 ),
new Y(2 ),
new Y(3 )
]
constructor() { }
ngOnInit(): void {
}
}
//导出类 Y{ //}
即如果你有不止一节课。 假设 XComponent 类和 Y 类,其中 Y 类在 XComponent 类中使用,然后在 @Component({}) 类之上或 XComponent 类之下为 Y 类编写代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.