andreasteich
andreasteich

Reputation: 153

How to inject html elements into custom component

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!

Upvotes: 4

Views: 2655

Answers (2)

fen89
fen89

Reputation: 589

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.

Upvotes: 3

Indragith
Indragith

Reputation: 1310

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

Upvotes: 8

Related Questions