2

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 {

}
11
  • 1
    still use templateUrl: './parent.component.html',? any reason you do not want to do this? Commented Mar 12, 2019 at 18:24
  • Yes of course this is one solution but I want my component to be as easy as possible to inherit, and for someone new jumping into the project, the mistake of not replacing the templateUrl path can be done. Commented Mar 12, 2019 at 18:25
  • As ABOS said, but also note, you can use relative paths to reference the parent HTML if it's in a different directory. Commented Mar 12, 2019 at 18:25
  • ../../parent.component.html to go back/up two directories. It gets messy fairly fast though. Commented Mar 12, 2019 at 18:27
  • Oh okay my bad I read it wrong. Yes of course relative paths but its in complete different folders. I am really open to the cleanest way of achieving this. I was thinking about writing a constant in the parent that returns the path of the parent template Commented Mar 12, 2019 at 18:29

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. Thanks for your share.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.