Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5: creating a parent component with an external template and overriding the inner part

I'm trying to create some sort of parent component that gives me some general appearance and logic for all my components, but in which I can write some specific logic and templating inside.

Look at these images:

Example of what I want to achieve

Both of these components have common traits: an upper part with a title and a "hide/show" button, and then, a "body" that differs between both of them. They also share that edit button and so, but my idea is to make that "body" part completely dynamic: that's the part of the component that I want to override with my implementation components.

In other words: I want to make an abstract class with Typescript that holds the template: the rectangle, the header and body, the title (which I want to override from the subclass)... and then, the "body" will be filled with the template provided by the subclass.

How can this be achieved in Angular? This far I've only seen ways of overriding completely the parent components templates, not to complement one with the other. I guess there must be a way to insert HTML code with Angular directives inside a component...

Thing is, which is it?

Thank you!

like image 771
Zerok Avatar asked Oct 16 '22 21:10

Zerok


1 Answers

Let's assume you named your component CardComponent and your selector is app-card.

For the title

You can simply use the @Input() component decorator to get the title string and use it in your generic CardComponent, see the angular documentation: https://angular.io/guide/component-interaction

For the body:

You can create your component containing the header and Edit button and then use the <ng-content> tag to get what's inside the component selector, for example:

<h2>{{title}}</h2>
<ng-content></ng-content>
<button>Edit</button>

And so you can use your card component like this:

<app-card [title]="Channel select">
    <!-- Insert your body html -->
</app-card>

PS: to learn more about ng-content, see this: https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b

like image 175
Mehdi Benmoha Avatar answered Oct 20 '22 18:10

Mehdi Benmoha