19

How would you inherit the template from a parent component in angular 4? Most materials exemplify overriding the parent component like this:

import { Component } from '@angular/core';
import { EmployeeComponent } from './employee.component';

@Component({
  selector: 'app-employee-list',
  template: `
    <h1>{{heading}}</h1>
    <ul>
      <li *ngFor="let employee of employees">
        {{employee.firstName}} {{employee.lastName}} <br>
        {{employee.email}} <br>
        <button (click)="selectEmployee(employee)">Select</button>
      </li>
    </ul>
  `
})
export class EmployeeListComponent extends EmployeeComponent {
  heading = 'Employee List';
}

but I want to inherit the template from EmployeeComponent, instead of overriding it with my own custom version. How can this be achieved?

4
  • 1
    You can't. Angular is not built to extend components, the typical pattern is to compose them. Commented Mar 14, 2018 at 7:09
  • I think you can use parent child interaction angular.io/guide/component-interaction Commented Mar 14, 2018 at 7:13
  • What do you want to achieve by doing so? As LakinduGunasekara already suggested can be used for interaction between components or you can also use services. Commented Mar 14, 2018 at 7:20
  • 4
    @IngoBürk actually it IS built to extend components. You cannot extend parent's template and style, but what you do have is component inheritance (inputs, outputs, host bindings etc.), which is very useful sometimes. Commented Mar 14, 2018 at 7:37

2 Answers 2

17

Since you have a child component, you could place it in the parent's directory, and give it an URL that references the parent.

@Component({
  selector: 'app-child',
  templateUrl: '../parent.component.html',
  styleUrls: ['../parent.component.scss']
})
Sign up to request clarification or add additional context in comments.

2 Comments

So obvious yet I didn't think of it. Thanks.
Agree. Template is not inherited. But if we want to use the same exact template, we can just load that exact template.
1

if you want to add something to parent template you can just plus it

@Component({
  selector: 'child',
  template: require('/path/to/child-template.html') + require('/path/to/parent-template.html')
})

(it is using webpack)

2 Comments

It does not work out of the box with Angular v11 This would need a html-loader to be configured in webpack. Unfortunately, Pug (ex Jade) template engine might be a solution for including partial templates (check tutoria here: smashingmagazine.com/2020/05/angular-templates-pug/l) However, the Pug loader for Angular doesn't support template inheritance...
@Const how is it possible to add two templates and get the one original template?

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.