In angular2, how can I determine if there is any ng content?

plnkr demo here

@Component({ selector: 'my-demo', template: `This is <ng-content select=".content"></ng-content>` }) export class DemoComponent { name = 'Angular'; } @Component({ selector: 'my-app', template: `<h1>Hello {{name}}</h1> <my-demo><div class="content">In Content</div></my-demo> ` }) export class AppComponent { name = 'Angular'; } 

I want conditionally ng-content like

 <ng-template *ngIf='hasContent(".content"); else noContent'> This is <ng-content select=".content"></ng-content> </ng-template> <ng-template #noContent>No content</ng-template> 

Is it possible in angular2?

+1
javascript angular angular2-template
source share
3 answers
 template: `This is <span #wrapper> <ng-content select=".content"></ng-content> </span>` 
 @ViewChild('wrapper') wrapper:ElementRef; ngAfterContentInit() { console.log(this.wrapper.innerHTML); // or `wrapper.text` } 

see also

  • Get the child component as a string
  • Access to restricted content
0
source share

The Günter Zöchbauer solution is acceptable, does not affect the use, let the component detect it, I also found an easier way to do it without json, using :empty

 <!-- must no content: https://css-tricks.com/almanac/selectors/e/empty/ --> < !--@formatter :off--> <div class="title"><ng-content select=".nav-title"></ng-content></div> < !--@formatter :on--> .title:empty { display: none; } 

Works for any html + css.

+1
source share

if you want to use the conditional operator with *ngIf and else yes, it is possible

 @Component({ selector: 'my-demo', template: `<div *ngIf='content; else noContent'> This is <ng-content select=".content"></ng-content> </div> <ng-template #noContent>No content</ng-template>` }) export class DemoComponent { name = 'Angular'; content = true} 

Demo

0
source share

All Articles