I have some use cases for inheritance and decoration (as in Decorator pattern) of components and directives in Angular 2.
The example is component with basic template that doesn't suit the case, to the point when it easier to define a new template instead of modifying the DOM of existing one programmatically. The rest of component metadata should be inherited.
Basically it is
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 {}
And more complicated case is
@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 {}
Notice that ThirdPartyComponent
has numerous inputs. There may be cases when it is beneficial to modify a component internally instead of wrapping it and modifying its behaviour from the outside. A wrapper component that enumerates them all in template and transfers them to ThirdPartyComponent
may be WET and dirty:
<third-party inputs="inputs" that="that" should="should" be="be" enumerated="enumerated">
Extra layout elements that are introduced by wrapper components may be prohibited in some cases.
ThirdPartyComponent
may be core component (a button) that is used by other third-party components. Then they should be affected too, so it may be necessary to 'decorate the decorator' all over the injector, not just extend it.
In Angular 1.x thirdPartyDirective
is a service that gives full access to component DDOs, so they could be decorated, extended, deep fried, etc. What are direct counterparts to this approach in Angular 2? If this breaks some rules and voids the warranty, it's ok.
How can a component/directive that doesn't export its metadata be extended?
How can the metadata of existing component be modified?
Your inputs will be inherited from the parent class automatically. Regarding properties of the Component
decorator itself, there is no native way to do that in Angular2. The Angular2 team won't provide support for this: https://github.com/angular/angular/issues/7968#issuecomment-219865739.
If you really want something like that, you need to implement with a custom decorator that updates annotations...
This article could interest you: