Search code examples
javascriptangular

How to check whether <ng-content> is empty? (in Angular 2+ till now)


Suppose I have a component:

@Component({
    selector: 'MyContainer',
    template: `
    <div class="container">
        <!-- some html skipped -->
        <ng-content></ng-content>
        <span *ngIf="????">Display this if ng-content is empty!</span>
        <!-- some html skipped -->
    </div>`
})
export class MyContainer {
}

Now, I would like to display some default content if <ng-content> for this component is empty. Is there an easy way to do this without accessing the DOM directly?


Solution

  • Wrap ng-content in an HTML element like a div to get a local reference to it, then bind the ngIf expression to ref.children.length == 0:

    template: `<div #ref><ng-content></ng-content></div> 
               <span *ngIf=" ! ref.children.length">
                  Display this if ng-content is empty!
               </span>`
    

    Updated for Angular 12; old logic ("ref.nativeElement.childNodes.length") gives error, as nativeElement is undefined nowadays.