Angular组件继承,保留父html

问题描述 投票:1回答:1

我在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 {

}
javascript angular angular6 angular2-template
1个回答
1
投票

您可以修改默认组件行为以使用基类中的模板,例如

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我不推荐这种方法:)

© www.soinside.com 2019 - 2024. All rights reserved.