类正在使用 Angular 功能,但没有装饰。请添加一个显式的 Angular 装饰器

abh*_*thi 63 typescript angular

我有这样一些组件CricketComponentFootballComponentTennisComponent等所有这些类有一些共同的特性: -TeamName, teamSize, players等,这是@Input()

现在我创建了一个BaseComponent类,在那里定义了所有这些属性,这个baseComponent类将被板球/足球/网球/等组件扩展。

基础组件.ts

export class BaseComponent {

    @Input() TeamName: string;
    @Input() teamSize: number;
    @Input() players: any;

}
Run Code Online (Sandbox Code Playgroud)

CricketComponent.ts

@Component({
  selector: 'app-cricket',
  templateUrl: './cricket.component.html',
  styleUrls: ['./cricket.component.scss']
})
export class cricketComponent extends BaseComponent implements OnInit {

  constructor() {
    super();
  }

  ngOnInit(): void {
  }

}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

src/app/base-screen.ts:4:14 中的错误 - 错误 NG2007:

类正在使用 Angular 功能,但没有装饰。请添加一个显式的 Angular 装饰器。

Rob*_*sen 70

您需要@Component向该基类添加一个装饰器(可能也应该声明abstract)。

这是您在 Angular 9 中可以逃脱的最低限度:

@Component({
  template: ''
})
export abstract class BaseComponent {

    @Input() teamName: string;
    @Input() teamSize: number;
    @Input() players: any;
}
Run Code Online (Sandbox Code Playgroud)

对于 Angular 10+,请参阅此答案

  • 我的意思是,感觉就像是黑客攻击。BaseComponent 不是角度分量。它只是一个由其他 Angular 组件扩展的打字稿类。 (12认同)
  • 实际上,对于 Angular10+ 使用 `@Directive()` ([link](/sf/answers/4817658121/)) (2认同)

Anh*_*ang 50

从 Angular 10 开始,您可以通过将装饰器 @Injectable() 添加到抽象基类中来解决此问题,如下所示:

@Injectable()
export abstract class BaseComponent {    
    @Input() teamName: string;
    @Input() teamSize: number;
    @Input() players: any;
}
Run Code Online (Sandbox Code Playgroud)

  • 正确的注释是“@Directive()”。请参阅 https://angular.io/guide/migration-undecorated-classes 或答案 /sf/answers/4817658121/ (16认同)
  • 这使得我的基类“undefined”定义了“@Input()”。我不得不切换到“@Directive()”。至少这是我在 Angular 11 中看到的,其他的不确定。 (5认同)
  • 这对于 Angular 10 来说是一件大事,因为他们改变了编译器对没有装饰器的类的严格程度 https://angular.io/guide/migration-injectable (2认同)

小智 24

另请参阅: 缺少 @Directive()/@Component() 装饰器迁移

前:

export class BaseComponent {
    @Input() TeamName: string;
    @Input() teamSize: number;
    @Input() players: any;
}
Run Code Online (Sandbox Code Playgroud)

后:

@Directive()
export class BaseComponent {
    @Input() TeamName: string;
    @Input() teamSize: number;
    @Input() players: any;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*d G 20

虽然在 using 中接受的答案是正确的@Component,但一个小缺点是它要求所有构造函数参数类型都可以由 DI 解析。因此,如果您的基类构造函数采用常量/文字(例如枚举)作为标志,则您将必须设置相应的 DI 提供程序/令牌才能使其编译。

但是,您也可以使用@Directive装饰器来解决 NG2007 ,这不需要 DI 兼容性