Is it possible to execute conditional content (switching) in angular 2+

I would like to provide default content that will only appear if the content is not broadcast.

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, if I would like to provide a default header. Is it possible; without acrobatics, for example, checking the contents in ngAfterContentInit ?

+7
angular
source share
1 answer

You can do it 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 will hide the title if the content is provided:

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

If no header is specified, then the display: none rule does not match.

Note: you need to disable content encapsulation in order to use this: encapsulation: ViewEncapsulation.None

+3
source share

All Articles