Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do conditional content projection (transclusion) in angular 2+

Tags:

angular

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?

like image 674
dovidweisz Avatar asked Jan 24 '17 15:01

dovidweisz


People also ask

What is a limitation of Mulitiple slot content projection?

Known limitations of our implementation are as follows: You cannot data-bind the slot's name attribute. You cannot data-bind the slot attribute. You cannot dynamically generate slot elements inside a component's view.

How do you style content that was projected using NG-content?

If you want to style the projected content within <ng-content>, you can do so using :host and ::ng-deep to apply styling to all nested elements within the <contact> component.

Which directive is used for content projection?

Create a component. This example uses the ngTemplateOutlet directive to render a given <ng-template> element, which you will define in a later step. You can apply an ngTemplateOutlet directive to any type of element.

How do you use Ngcontent?

The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content.


1 Answers

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

like image 127
William Neely Avatar answered Oct 29 '22 16:10

William Neely