I was just learning the use of Transluction
in angular2
from this tutorial:
https://scotch.io/tutorials/angular-2-transclusion-using-ng-content
I was able to use the <ng-content>
tag for some content like:
<ng-content select="[my-block-header]"></ng-content>
and it lies in component where my-block
selector is attached.
It renders the content from my other component as:
<my-block>
<div class="box-header" my-block-header> <--added the slot selector here
<h3 class="box-title">
My title
</h3>
</div>
</my-block>
The issue is:
Is it possible to add the default value to the <ng-content>
block which could be used if we didn't pass any value?
As for now if there is no value passed there will be blank page in it's position.
Edit:
When i was trying to test there was newer version of zone.js
which was not allowing the correct error to be displayed, therefore i was getting the error as:
Cannot set property 'stack' of undefined ; Zone: <root> ;
Task: Promise.then ; Value: TypeError: Cannot set property 'stack' of undefined
But when i changed the version of zone.js
to 0.7.2
the error was clearly mentioned in the console as:
zone.js:392 Unhandled Promise rejection: Template parse errors:
<ng-content> element cannot have content.
So, it confirms that there can't be any default value set to <ng-content>
Use the :host /deep/ selector. If you want to use the shadow DOM polyfill and style your components using the style or styleUrls attribute of the Component decorator, select the element with :host , then ignore the shadow DOM polyfill with the /deep/ child selector. :host will select the element.
Content projection is a pattern in which you insert, or project, the content you want to use inside another component. For example, you could have a Card component that accepts content provided by another component.
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.
From angular 10 the following works:
<div #ref><ng-content></ng-content></div>
<ng-container *ngIf="!ref.hasChildNodes()">
Default Content
</ng-container>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With