Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject html elements into custom component

Tags:

angular

I Need to pass html Elements into a custom created components via the template file. Let's imagine I have a component called <app-card></app-card> that represents a Card layout with specific style, but I don't want to create this component everytime from Scratch when I Need it. So it would be a good Approach I think to create a custom UI component for this element. But now when I use this component, I want to pass some other html Elements into it, for example a H2 and some p-tags:

<app-card>
  <h2>New child I passed</h2>
  <p>And another one</p>
</app-card>

When I test it, this way wouldn't work. Does anyone know how I can achive that nested components?

Thank you very much!

like image 592
andreasteich Avatar asked Oct 16 '25 09:10

andreasteich


2 Answers

ng-content will be helpful in creating the configurable components. You need to use inside the app-card component. Content that has been placed within the opening and the closing tags of the app-card will be projected in

app-card component

<div>
    <ng-content></ng-content>
</div>

Custom component

<app-card>
  <h2>New child I passed</h2>
  <p>And another one</p>
</app-card>

Here h2 and p tag will be rendered inside the ng-content. For more info search for content projection in angular

like image 153
Indragith Avatar answered Oct 19 '25 01:10

Indragith


You need to use ng-content inside your custom component to make it work.

app-card.component.html:

<div>
  <ng-content></ng-content>
</div>

Then you can use it like you wanted to:

<app-card>
  <h2>New child I passed</h2>
  <p>And another one</p>
</app-card>

You can go a step further, if you need to and create multiple projections:

<div>
    <div class="head">
        <ng-content select="h1"></ng-content>
    </div>
    <div class="body">
        <ng-content select="div"></ng-content>
    </div>
    <div class="footer">
        <ng-content></ng-content>
    </div>
</div>

And then you can use it like this:

<app-card>
    <h1>My card title</h1>
    <div>My special div</div>
    <span>All the rest which doesn't belong to a special selector goes into the default ng-content</span>
</app-card>

Hope this helps.

like image 37
fen89 Avatar answered Oct 19 '25 00:10

fen89