扩展/装饰Angular 2的组件和指令

Extending/decorating Angular 2 components and directives

本文关键字:组件 指令 装饰 Angular 扩展      更新时间:2023-09-26

我有一些在Angular 2中对组件和指令进行继承和装饰的用例。

这个例子是一个基本模板的组件,它不适合这种情况,以至于更容易定义一个新模板,而不是通过编程修改现有模板的DOM。其余的组件元数据应该被继承。

基本上是

export const BASE_SOME_COMPONENT_METADATA = { ... };
@Component(BASE_SOME_COMPONENT_METADATA);
export class BaseSomeComponent { ... }
...
import { BaseSomeComponent, BASE_SOME_COMPONENT_METADATA } from '...';
@Component(Object.assign({}, BASE_SOME_COMPONENT_METADATA, { template: '...' });
export class SomeComponent extends BaseSomeComponent {}

更复杂的情况是

@Component({ ... });
export class ThirdPartyComponent {
  @Input() ...;
  @Input() ...;
  @Input() ...;
  ...
}
...
import { ThirdPartyComponent as BaseThirdPartyComponent } from '...';
@Component({
  // may modify or replace any of the original properties
  template: ...,
  styles: ...
  ...
});
export class ThirdPartyComponent extends BaseThirdPartyComponent {}

注意ThirdPartyComponent有许多输入。在某些情况下,在内部修改组件比从外部包装组件并修改其行为更有益。在模板中枚举它们并将它们传输到ThirdPartyComponent的包装器组件可能是湿的和脏的:

<third-party inputs="inputs" that="that" should="should" be="be" enumerated="enumerated">
在某些情况下,包装器组件引入的额外布局元素可能是被禁止的。

ThirdPartyComponent可能是核心组件(按钮),被其他第三方组件使用。那么它们也应该受到影响,所以可能有必要在整个注入器上"装饰装饰器",而不仅仅是扩展它。

在Angular 1中。x thirdPartyDirective是一个提供对组件DDOs的完全访问权限的服务,因此它们可以被装饰、扩展、油炸等。在Angular 2中,与这种方法直接对应的是什么?如果这违反了某些规则,使保修无效,也没关系。

不导出元数据的组件/指令如何被扩展?

如何修改现有组件的元数据?

您的输入将自动从父类继承。至于Component装饰器本身的属性,在Angular2中没有原生的方法来实现。Angular2团队不会为此提供支持:https://github.com/angular/angular/issues/7968#issuecomment-219865739.

如果你真的想要这样的东西,你需要实现一个自定义的装饰器来更新注释…

你可能会对这篇文章感兴趣:

  • https://medium.com/@ttemplier angular2 -修饰符和类继承- 905921 dbd1b7 # .8r5fuys6l