As I delve into creating Web apps using Angular2 with TypeScript, one aspect that stands out is the need to import CustomElements (such as Components and Directives, Validators) in each individual Component file. This results in repetitive code like directives: [...]
, as shown below:
// my_component_1.component.ts
@Component({
selector: 'my-component-1',
directives: [
ROUTER_DIRECTIVES,
MyDirective1,
MyDirective2,
MyValidator1,
MyValidator2,
...
],
})
// my_component_2.component.ts
@Component({
selector: 'my-component-2',
directives: [
ROUTER_DIRECTIVES,
MyDirective1,
MyDirective2,
MyValidator1,
MyValidator2,
...
],
})
// my_component_3.component.ts
@Component({
selector: 'my-component-3',
directives: [
ROUTER_DIRECTIVES,
MyDirective1,
MyDirective2,
MyValidator1,
MyValidator2,
...
],
})
I start pondering if there's a more efficient way to import CustomComponents without the repetitive directives: [...]
declarations. Is there a method akin to event bubbling or prototype chain where child Components can inherit the imported CustomElements of their parent Components?
// parent.component.ts
@Component({
selector: 'parent',
directives: [MyDirective1, ...],
})
// child.component.ts
@Component({
selector: 'child',
template: `
// Here, MyDirective is accessible due to being imported by ParentComponent.
<div my-directive></div>
`,
})