Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If ng-content has content or empty Angular2

I am trying to understand how to create an if to show when a ng-content is empty.

<div #contentWrapper [hidden]="isOpen">
    <ng-content ></ng-content>
</div>

<span *ngIf="contentWrapper.childNodes.length == 0">
    <p>Display this if ng-content is empty!</p>
</span>

I've tried to use that one to show a display data when the content is empty but even if the information is empty doesn't show the <span> tag

Thanks, always grateful for your help.

like image 294
rodboc Avatar asked Jun 17 '16 06:06

rodboc


People also ask

What does ng content do?

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.

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.

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.

How do ng templates work?

ng-template is an Angular element that is used for rendering HTML in a template. However, it is not rendered directly on DOM. If you include an ng-template tag to a template, the tag and the content inside it will be replaced by comment upon render.


1 Answers

Use children instead of childNodes. Angular creates comment nodes for *ngIf* which are counted bychildNodes`

<div #contentWrapper [hidden]="isOpen">
    <ng-content ></ng-content>
</div>

<span *ngIf="contentWrapper.children.length == 0">
    <p>Display this if ng-content is empty!</p>
</span>  

Plunker example

like image 160
Günter Zöchbauer Avatar answered Oct 20 '22 23:10

Günter Zöchbauer