159

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?

1
  • FYI, I know the accepted answer works, but I think it's better style to pass in a "useDefault" type input parameter to components, defaulted to false.
    – bryan60
    Oct 31, 2017 at 13:51

15 Answers 15

151

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.

17
  • 35
    Is there no alternative way to this? Because this is ugly, compared to Aurelia fallback slots
    – Astronaut
    Jan 11, 2017 at 18:53
  • 22
    It's safer to use ref.children.length. childNodes will contain text nodes if you format your html with spaces or new lines, but children will still be empty.
    – parliament
    Jan 16, 2017 at 8:22
  • 7
    There is a feature request for a better method on the Angular issue tracker: github.com/angular/angular/issues/12530 (might be worth adding a +1 there).
    – eppsilon
    Jan 23, 2017 at 18:54
  • 6
    I was about to post that this didn't seem to be working until I realized that I used the example of ref.childNodes.length == 0 instead of ref.children.length == 0. It would help a bunch if you could edit the answer to be consistent. Easy mistake, not bashing you. :) May 8, 2017 at 14:25
  • 13
    I followed this example and it works fine for me. But I used !ref.hasChildNodes() instead of ref.nativeElement.childNodes.length == 0 Apr 15, 2019 at 9:34
71

EDIT 17.03.2020

Pure CSS (2 solutions)

Provides default content if nothing is projected into ng-content.

Possible selectors:

  1. :only-child selector. See this post here: :only-child Selector

    This one require less code / markup. Support since IE 9: Can I Use :only-child

  2. :empty selector. Just read further.

    Support from IE 9 and partially since IE 7/8: https://caniuse.com/#feat=css-sel3

HTML

<div class="wrapper">
    <ng-content select="my-component"></ng-content>
</div>
<div class="default">
    This shows something default.
</div>

CSS

.wrapper:not(:empty) + .default {
    display: none;
}

In case it's not working

Be aware of, that having at least one whitespace is considered to not beeing empty. Angular removes whitespace, but just in case if it is not:

<div class="wrapper"><!--
    --><ng-content select="my-component"></ng-content><!--
--></div>

or

<div class="wrapper"><ng-content select="my-component"></ng-content></div>
6
  • 5
    By far this was the best solution for my use case. I wasn't remembering we had an empty css pseudoclass Dec 4, 2018 at 13:38
  • 1
    @Stefan the default content will be rendered anyway...it will be only hide. So, for complex default content this is not the best solution. Is this right?
    – Oscar TJ
    Mar 30, 2020 at 12:31
  • 2
    @BossOz You are right. It will be rendered (constructor etc. will be called if you have an angular component). This solution works only good for dumb views. If you have complex logic, involving loading or stuff like that, your best bet in my opinion is to write a structural directive, which can get a template / class (however you want to implement it) and depending on the logic, then render the desired component or the default one. The comment section is way too small for an example. I comment again for another example we have in one of our apps. Mar 30, 2020 at 12:47
  • One way would be having a component selecting the ContentChildren via a Directive (query with DirectiveClass, but usage as structural directive, so no initial bootstrapping involved with just having the markup): <loader [data]="allDataWeNeed"> <desired-component *loadingRender><desired-component> <other-default-component *renderWhenEmptyResult></other-default-component> </loader> and in the loading component, you could show perceived performance loading, while the data is loading. You can write / solve it in different ways. This is one demonstration how you could solve it. Mar 30, 2020 at 12:52
  • By far the best most elegant solution! thanks man!
    – Mehdi
    Dec 28, 2020 at 21:05
48

There some missing in @pixelbits answer. We need to check not only children property, because any line breaks or spaces in parent template will cause children element with blank text\linebreaks. Better to check .innerHTML and .trim() it.

Working example:

<span #ref><ng-content></ng-content></span>
<span *ngIf="!ref.innerHTML.trim()">
    Content if empty
</span>
5
  • Can we use this method to check whether child element is empty and hide the parent if so? I tried, no luck Jul 12, 2019 at 11:54
  • @KavindaJayakody Yes, this will check child element for empty. Show your code.
    – lfoma
    Jul 12, 2019 at 12:53
  • 1
    *ngIf="!ref.innerHTML.trim()" This part will cause performance issues. Trim is O(n).
    – RandomCode
    Feb 12, 2020 at 13:40
  • 3
    @RandomCode is right, the function will be called multiple times. A better way is to check element.children.length or element.childnodes.length, depending on what you want to ask for. Oct 7, 2020 at 5:17
  • It says "ref" is not declared as a variable. Element reference is not working on ng-content. I am using angular 11
    – Deb
    Feb 4, 2021 at 18:35
32

When you inject the content add a reference variable:

<div #content>Some Content</div>

and in your component class get a reference to the injected content with @ContentChild()

@ContentChild('content') content: ElementRef;

so in your component template you can check if the content variable has a value

<div>
  <ng-content></ng-content>
  <span *ngIf="!content">
    Display this if ng-content is empty!
  </span>    
</div> 
1
  • 12
    The OP asked for whether or not ngContent is empty - this means <MyContainer></MyContainer>. Your solution expects users to create a sub-element under MyContainer: <MyContainer><div #content></div></MyContainer>. While this is a possibility, I would not say this is superior. Oct 3, 2018 at 2:53
18

If you want to display a default content why dont you just use the 'only-child' selector from css.

https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child

for eg: HTML

<div>
  <ng-content></ng-content>
  <div class="default-content">I am default</div>
</div>

css

.default-content:not(:only-child) {
   display: none;
}
2
  • Rather smart solution, if you don't want to deal with ViewChild and stuffs in the Component. I like it! Oct 6, 2020 at 21:09
  • Please notice that transclude content must be an HTML node (not only text) Oct 6, 2020 at 21:15
13

Inject elementRef: ElementRef and check if elementRef.nativeElement has any children. This might only work with encapsulation: ViewEncapsulation.Native.

Wrap the <ng-content> tag and check if it has children. This doesn't work with encapsulation: ViewEncapsulation.Native.

<div #contentWrapper>
  <ng-content></ng-content>
</div>

and check if it has any children

@ViewChild('contentWrapper') contentWrapper;

ngAfterViewInit() {
  contentWrapper.nativeElement.childNodes...
}

(not tested)

9
  • 4
    I downvoted this because of the use of @ViewChild. While "Legal", ViewChild should not be used for accessing child-nodes within a template. This is an antipattern because, while parents may know about children, they should not Couple to them as it usually leads to Pathological Coupling; a more appropriate form of data-transport or request-handling is to use event-driven methodologies.
    – Cody
    Aug 30, 2017 at 17:47
  • 8
    @Cody thanks for posting a comment to your downvote. Actually I don't follow your argumentation. The template and the components class are a single unit - a component. I don't see why accessing the template from the code should be an antipattern. Angular (2/4) has almost nothing in common with AngularJS except that both are web frameworks and the name. Aug 30, 2017 at 18:05
  • 2
    Gunter, you make two really good points. Angular should not necessarily hatch with a stigma from the ways of AngularJS. But I'd mark that the first point (and those I've made above) fall toward the philosophical gutter of engineering. That said, I've become something of an expert on Software Coupling and I'd advise against [at least heavy] use of @ViewChild. Thanks for adding some balance to my comments -- I find both of our comments just as worthy of consideration as the other.
    – Cody
    Aug 30, 2017 at 22:04
  • 2
    @Cody perhaps your strong opinion about @ViewChild() comes from the name. "Children" aren't necessarily children, they are just the declarative part of the component (as I see it). If the component instances created for this markup are accesses, this if of course a different story, because it would require knowledge about at least their public interface and this would actually create tight coupling. This is a very interesting discussion. It worries me that I don't have enough time to think about such matters because with such frameworks too often time is burned to find any way at all. Aug 31, 2017 at 3:19
  • 5
    Not exposing this in the API is the real anti-pattern :-( Jun 15, 2018 at 21:24
10

Sep 2021

There is another technique to accomplish the default content if not provided from the implementation component by using *ngTemplateOutlet directive which allows us to have the customization more control:

Example in source component:

import { Component, ContentChild, TemplateRef } from '@angular/core';
@Component({
  selector: 'feature-component',
  templateUrl: './feature-component.component.html',
})
export class FeatureComponent {
  @ContentChild('customTemplate') customTemplate: TemplateRef<any>;
}

Then in HTML template:

<ng-container
  [ngTemplateOutlet]="customTemplate || defaultTemplate"
></ng-container>

<ng-template #defaultTemplate>
  <div class="default">
    Default content...
  </div>
</ng-template>

target component:

<!-- default content -->

<feature-component></feature-component>


<!-- dynamic content -->

<feature-component>
  <ng-template #customTemplate>
    <div> Custom group items. </div>
  </ng-template>
</feature-component>
3
  • This did not work for me.
    – Unknown
    Oct 14, 2021 at 9:23
  • @Unknown May I know the problem you had?
    – Ravi Anand
    Oct 14, 2021 at 14:48
  • 2
    This is the only solution that lets me remove the element completely if no content was passed in from the outer control. I was able to do <mat-dialog-actions *ngIf="actionsTemplate"><ng-container [ngTemplateOutlet]="actionsTemplate"></ng-container></mat-dialog-actions>. Now if there's no content, mat-dialog-actions is gone rather than being empty and taking up space.
    – Roobot
    Oct 18, 2022 at 21:18
3

In my case I have to hide parent of empty ng-content:

<span class="ml-1 wrapper">
  <ng-content>
  </ng-content>
</span>

Simple css works:

.wrapper {
  display: inline-block;

  &:empty {
    display: none;
  }
}
3

With Angular 10, it has changed slightly. You would use:

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

I've implemented a solution by using @ContentChildren decorator, that is somehow similar to @Lerner's answer.

According to docs, this decorator:

Get the QueryList of elements or directives from the content DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.

So the necessary code in the parent component will be:

<app-my-component>
  <div #myComponentContent>
    This is my component content
  </div>
</app-my-component>

In the component class:

@ContentChildren('myComponentContent') content: QueryList<ElementRef>;

Then, in component template:

<div class="container">
  <ng-content></ng-content>
  <span *ngIf="*ngIf="!content.length""><em>Display this if ng-content is empty!</em></span>
</div>

Full example: https://stackblitz.com/edit/angular-jjjdqb

I've found this solution implemented in angular components, for matSuffix, in the form-field component.

In the situation when the content of the component is injected later on, after the app is initialised, we can also use a reactive implementation, by subscribing to the changes event of the QueryList:

export class MyComponentComponent implements AfterContentInit, OnDestroy {
  private _subscription: Subscription;
  public hasContent: boolean;

  @ContentChildren('myComponentContent') content: QueryList<ElementRef>;

  constructor() {}

  ngAfterContentInit(): void {
    this.hasContent = (this.content.length > 0);
    this._subscription = this.content.changes.subscribe(() => {
      // do something when content updates
      //
      this.hasContent = (this.content.length > 0);
    });
  }

  ngOnDestroy() {
    this._subscription.unsubscribe();
  }

}

Full example: https://stackblitz.com/edit/angular-essvnq

2

<ng-content #ref></ng-content> shows error "ref" is not declared. The following is working in Angular 11 (Probably 10 also):

<div #ref><ng-content></ng-content></div>
  <ng-container *ngIf="!ref.hasChildNodes()">
       Default Content
  </ng-container>
1

in angular 11 I use this and works fine.

template file :

 <h3 class="card-label" #titleBlock>
      <ng-content select="[title]" ></ng-content>
 </h3>

component:

@ViewChild('titleBlock') titleBlock: ElementRef;
hasTitle: boolean;


ngAfterViewInit(): void {
    if (this.titleBlock && this.titleBlock.nativeElement.innerHTML.trim().length > 0)
    {
        this.hasTitle=  true;
    }
    else
    {
       this.hasTitle=  false;
    }
}
1

In Angular 12, the console reports the following for me:

Property 'nativeElement' does not exist on type 'HTMLElement'

There seems to exist a specific attribute childElementCount which you can use for this case.

As a consequence, I used this successfully, which does not wrap the dynamic content into additional elements/tags:

<div class="container">
  <!-- some html skipped -->

  <ng-container #someContent>
    <ng-content></ng-content>
  </ng-container>
  <span 
    *ngIf="
      someContent.childElementCount === undefined || 
      someContent.childElementCount === 0
    "
  >
    Display this if ng-content is empty!
  </span>

  <!-- some html skipped -->
</div>
1
  • 2
    somehow hasChildNodes() is not working for me. this helped
    – joyBlanks
    Aug 11, 2021 at 11:10
1

This solution has worked for me (on angular version 12.0.2). Note that this will probably not work if your content is dynamic and changes from empty to non-empty (or the other way) after the component was already loaded. That can be fixed by adding code that changes hasContent inside ngOnChanges.

Example:

import {Component, ViewChild, AfterViewInit} from '@angular/core';

@Component({
    selector: 'my-component',
    template: '<div [ngClass]="[hasContent ? 'has-content' : 'no-content']">
        <span #contentRef>
            <ng-content></ng-content>
        </span>
    </div>']
})
export class Momponent implements AfterViewInit {

    @ViewChild('contentRef', {static: false}) contentRef;

    hasContent: boolean;

    ngAfterViewInit(): void {
        setTimeout(() => {
            this.hasContent = this.contentRef?.nativeElement?.childNodes?.length > 1;
        });
    }
}
-1

You can split it into two components:

@Component({
    selector: 'MyContainer',
    template: `
    <div class="container">
        <!-- some html skipped -->
        <ng-content></ng-content>
        <!-- some html skipped -->
    </div>`
})
export class MyContainer {
}

@Component({
    selector: 'MyContainerNoContent',
    template: `
    <MyContainer>
        <span>Display this if ng-content is empty!</span>
    </MyContainer>`
})
export class MyContainerNoContent {
}

and use MyContainer if you want to add content and MyContainerNoContent for the default content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.