【问题标题】:Extending/decorating Angular 2 components and directives扩展/装饰 Angular 2 组件和指令
【发布时间】:2016-10-31 01:26:06
【问题描述】:

我有一些 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 的包装器组件可能是 WET 和脏的:

<third-party inputs="inputs" that="that" should="should" be="be" enumerated="enumerated">

在某些情况下,包装组件引入的额外布局元素可能会被禁止。

ThirdPartyComponent 可能是其他第三方组件使用的核心组件(按钮)。那么它们也应该受到影响,因此可能需要在整个注入器上“装饰装饰器”,而不仅仅是扩展它。

在 Angular 1.x 中,thirdPartyDirective 是一项服务,它提供对组件 DDO 的完全访问权限,因此可以对它们进行修饰、扩展、油炸等。Angular 2 中这种方法的直接对应物是什么? 如果这违反了某些规则并导致保修失效,没关系。

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

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

【问题讨论】:

    标签: javascript typescript angular angular2-directives ecmascript-next


    【解决方案1】:

    您的输入将自动从父类继承。关于Component 装饰器本身的属性,Angular2 中没有本地方法可以做到这一点。 Angular2 团队不会为此提供支持:https://github.com/angular/angular/issues/7968#issuecomment-219865739

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

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

    【讨论】:

    • 输入的问题是指在模板中强制执行&lt;originalComponent all="all" the="the" inputs="inputs" that="that" should="should" be="be" enumerated="enumerated"&gt; 的包装器组件。我在 Ng 中分享了这些内容,最后以编程方式在 compile 中添加了 attrs。我正在尝试找出在 Ng2 中有效地做这些事情的方法。
    • 顺便说一句,很好的阅读,谢谢你的链接。实际上,我发现您的this answer 大部分都回答了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2017-08-24
    • 2016-08-18
    相关资源
    最近更新 更多