11

I would like to provide default content that would appear only if content is not transcluded.

For example Here is my component template:

<article>
    <header>
        <ng-content select="[header]"></ng-content>
    </header>
    <section>
        <ng-content></ng-content>
    </section>
</article>

I can use it like this:

<my-component>
    <h1 header>This is my header</h1>
    <p>This is my content</p>
</my-component>

Now what if i wanted to provide a default header. Is it possible; without acrobatics like checking for content in ngAfterContentInit?

dovidweisz
  • 1,215
  • 13
  • 24
  • 1
    Take a look at this answer http://stackoverflow.com/a/38692980/373655 . Not sure if a more elegant solution exists that doesn't require `ngAfterContentInit` – rob Jan 24 '17 at 15:54
  • Also, can you alias a projection? `` – Cody Jan 26 '17 at 07:11

2 Answers2

5

You can do this with pure CSS! Imagine you have the following

<ng-content select=".header"></ng-content>
<h1 class="default-header">
     This is my default header
</h1>

then the following CSS would hide the header if the content is supplied:

.header + .default-header {
    display: none;
}

If no header is supplied, then the display:none rule isn't matched.

Note, you'll have to turn off content encapsulation to use this: encapsulation: ViewEncapsulation.None

William Neely
  • 1,923
  • 1
  • 20
  • 23
0

It is possible.

You should configure that component to accept an ng-template element that contains the content you want to conditionally render.

For more info https://angular.io/guide/content-projection#conditional-content-projection