Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide a fallback for empty ng-content in Angular?

Tags:

angular

Say, I have a component that accepts ng-content in its template:

but I would like the component to display some default content as a fallback, in case nothing is provided as ng-content. Is there a *ngIf type of directive that I could apply as a test whether ng-content is not empty?

like image 554
user776686 Avatar asked Feb 28 '17 08:02

user776686


People also ask

Can we style 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.

What is the difference between Ng-content ng-container and ng-template?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.

What is Ng-content content projection?

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.


1 Answers

You can check for projected content yourself and show alternative content when none was found:

@Component({
  template: `
    <div *ngIf="hasContent">alternative content</div>
    <div #wrapper>
      <ng-content></ng-content>
    </div>
  `
})
class MyComponent implements AfterContentInit {
  @ContentChild('wrapper') wrapper:ElementRef;
  hasContent = false;
  ngAfterContentInit() {
    this.hasContent = this.wrapper.childNodes.length > 0;
  }
}
like image 57
Günter Zöchbauer Avatar answered Oct 01 '22 18:10

Günter Zöchbauer