user2992476
user2992476

Reputation: 1646

Inheritance of component angular 6 templates

We know we can extend an angular component but I would like to also extend the template associated. I mean, for instance, I could define an abstract component with its template with kind of skeleton, and then in the children would be forced to implements not only the abstract class methods and so on, but also the "empty gaps" of the skeleton html template.

Up to now, I have to completely redefine the template in the child. I know that I could create another component but that a relationship by association. It's annoying because I have to create an abstract class to be extend and then a component to redefine the template.

How do you do that?

Upvotes: 5

Views: 5984

Answers (2)

VnC
VnC

Reputation: 2016

You can use ng-content and ng-template.

In your abstract component

@Component({
  selector: 'abstract-component',
  template: /*html*/`
    <abstract-template>
      <div>
        <ng-content *ngTemplateOutlet="customTemplate || defaultTemplate"></ng-content>
      </div>
    </abstract-template>

    <ng-template #defaultTemplate>
      ... default HTML ...
    </ng-template>
  `,
})

then in your new component, where you want to adjust or customise the template, you should add:

<abstract-template
  ... inputs ...
>
  <ng-template #customTemplate>
    ... your custom HTML ...
  </ng-template>
</abstract-template>

ngTemplateOutlet will pick the customTemplate if it is passed through ng-template

Upvotes: 0

Ren&#233; Winkler
Ren&#233; Winkler

Reputation: 7058

This is not possible. What could be useful to you is content projection

https://blog.angular-university.io/angular-ng-content/

Upvotes: 2

Related Questions