Reputation: 4152
I use a lot of inheritance between my Angular components.
Sometimes, I would like to be able to inherit from a specific component, and not provide some html for the child (because it is always going to be the same as the parent) which leads to duplicate code everywhere.
What is the best way to achieve this ?
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class Parent {
}
@Component({
selector: 'app-child',
template: '', <-- you have to provide a template
})
export class Child extends Parent {
}
Upvotes: 1
Views: 1905
Reputation: 3823
You can modify default component behavior to use template from base class, e.g.
function MyComponent(cfg: any) {
return function (constructor: Function) {
let base = (Object.getPrototypeOf(constructor.prototype).constructor);
cfg.template = (<any>base).__annotations__[0].template;
return Component(cfg)(constructor);
}
}
@MyComponent({
selector: 'my-app-child',
styleUrls: ['./app.component.css']
})
export class AppChildComponent extends AppComponent {
}
a simple demo https://stackblitz.com/edit/angular-swaanp?file=src%2Fapp%2Fapp.component.ts
PS I don't recommend this approach :)
Upvotes: 2