Angular default ng-content - How to use it
What is Angular's default content when using ng-content
?
And how do you use it?
Let's start with a simple example.
This is default content.
<ng-content>
Default Content
</ng-content>
You simply fill the element with some default content.
How does it work?
Let's say we have two component templates.
<my-component>
<ng-content select="header"></ng-content>
</my-component>
And the first component is used inside of a main app component like this.
<app-main>
<my-component>
<header>Hello World</header>
</my-component>
<app-main>
What we've done is just created a main component and then inserted data into my-component
using the ng-content
element.
But with recent updates to Angular the ng-content
element can now contain default content.
Let's remove the header value from the main component.
<app-main>
<my-component>
<header></header>
</my-component>
<app-main>
Now, obviously the header will be empty.
But I can change my-component
to have a default display value by simply putting content inside the ng-content
element. Like this.
<my-component>
<ng-content select="header">Default Header</ng-content>
</my-component>
And now the default content is displayed.
But why would you want to use a default display value with ng-content
?
One reason would be is that defaulting to null
has been called the billion dollar mistake. And this can easily be fixed by setting a default value.
Whenever you need a default behavior that can be replaced on-demand then make sure you display a default value inside of ng-content
.
And that, my Angular friend, is how to use the ng-content default option.
Daniel Kreider - Angular Developer