【问题标题】:Angular 10 Upgrade: Why use @Directive() instead of @Component() for abstract (component) classes?Angular 10 升级:为什么对抽象(组件)类使用 @Directive() 而不是 @Component()?
【发布时间】:2020-12-20 12:49:17
【问题描述】:

我最近将我的 Angular 应用从 v9 升级到了 v10。

我注意到不再支持未修饰的类。见here

所以在ng upgrade 期间,我没有装饰的抽象组件已更改为具有@Directive() 装饰器。

例如

export abstract class AbstractFormControl implements ControlValueAccessor { ... }

改成了

@Directive()
export abstract class AbstractFormControl implements ControlValueAccessor { ... }

为什么 Angular 使用@Directive@Component 不是更好的方法,因为类是一个组件而不是一个指令?目的是什么?

【问题讨论】:

  • 组件本质上是一个带有模板的指令。当基类没有关联的模板时,将其装饰为指令而不是组件更有意义。如果您需要了解为什么需要进行此更改,您可以查看here

标签: angular angular10


【解决方案1】:

组件要求你指定templatetemplateUrl,不能与 一个抽象类。

正如 cmets 中提到的 - 组件是一种特殊类型的指令。所以可以继承抽象指令。

【讨论】:

  • 在我看来 @Component({ template: '' }) 可以很好地作为 Angular 12 中抽象类的装饰器,尽管 @Directive 可能是首选。
  • 我不知道这会产生什么影响——这是否意味着您可以路由到它。 Angular 团队推荐的方法是使用 Directive,因此迁移更改添加了 @Directive
猜你喜欢
  • 2013-09-21
  • 2012-08-20
  • 2020-07-06
  • 1970-01-01
  • 2020-08-10
  • 2011-01-10
  • 2010-10-15
  • 2012-04-24
  • 1970-01-01
相关资源
最近更新 更多