抽象基类上的 Angular 9 装饰器

Joh*_*nko 7 angular angular9

我正在努力将我的项目从 Angular 8 升级到 9,并且在扩展类时遇到了新需求的问题。

根据 Angular 的文档

使用 Angular 功能的未修饰基类

从版本 9 开始,不推荐使用未修饰的基类:

  • 使用 Angular 功能
  • 由指令或组件扩展

Angular 生命周期挂钩或以下任何 Angular 字段装饰器都被视为 Angular 功能:

  • @Input()
  • @Output()
  • @HostBinding()
  • @HostListener()
  • @ViewChild()/@ViewChildren()
  • @ContentChild()/@ContentChildren()

对于@Component装饰器,它需要基类上的templateor 。templateURL添加任一都会导致子类不呈现其模板。

例如,以下结果不会在视图上呈现任何内容:

@Component({
  template: ''
})
export abstract class BaseComponent<T extends AbstractSuperEntity> extends Toggler implements OnChanges {
  @Input()
  year: number | string

  constructor(service: MyService) {

  }

  ngOnChanges() {
  }
}

@Component({
  templateUrl: 'my.component.html',
  selector: 'my-component'
})
export class MyComponent extends BaseComponent<AbstractSuperEntity> {

  constructor(service: MyService) {
    super(service);
  }

}
Run Code Online (Sandbox Code Playgroud)

我尝试更改基类以使用templateUrl指向空 html 的方法,但这也不起作用。

Pie*_*Duc 14

您必须添加一个空@Directive()装饰器。据我所知,这应该足够了:

@Directive()
export abstract class BaseComponent<T extends AbstractSuperEntity> extends Toggler implements OnChanges {
  @Input()
  year: number | string

  constructor(service: MyService) {

  }

  ngOnChanges() {
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我还应该指出,Angular 提供的示例显示了使用“@Directive()”的基本指令和使用“@Component({...})”的基本组件。因此,当基础也是抽象的并且无意于自己生存时,它们的实际含义有点令人困惑。https://angular.io/guide/migration-undecorated-classes (2认同)