我在Angular组件之间使用了很多继承。
有时,我希望能够继承特定的组件,而不是为子级提供一些html(因为它总是与父级相同),这导致到处都是重复的代码。
实现这一目标的最佳方法是什么?
@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 {
}
您可以修改默认组件行为以使用基类中的模板,例如
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 {
}
一个简单的演示https://stackblitz.com/edit/angular-swaanp?file=src%2Fapp%2Fapp.component.ts
PS我不推荐这种方法:)