Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  103] [ 3]  / answers: 1 / hits: 87763  / 8 Years ago, sat, january 30, 2016, 12:00:00

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?


More From » angular

 Answers
43

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.



[#63500] Thursday, January 28, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anabeldaliad

Total Points: 552
Total Questions: 107
Total Answers: 120

Location: Hungary
Member since Mon, Feb 21, 2022
2 Years ago
;