Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Default content for ng-content when using ngIf

I have this Angular 9 component, named inner:

<div #ref>
    <ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.hasChildNodes()">
    <div>Default value</div>
</ng-container>

It will be displayed "Some content" if I use it in a parent component this way:

<inner><div content>Some content</div><inner>

It will be displayed "Default value" if I use it in a parent component this way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<inner><inner>

But in this case:

<inner><div content *ngIf="false">Some content</div><inner>

nothing is displayed. "Some content" is not displayed because condition is false, but also "Default value" is not displayed.

How can I show "Default value" in this case?

I could use a class instead of attribute in the select. But I always prefer use classes to be used by CSS, not for this kind of logic.

>Solution :

You can use another prop from HTMLDivElement and get things work, like this:

<div #ref>
    <ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.childElementCount">
    <div>Default value</div>
</ng-container>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading