In angular2, how can I detect is there any ng-content?
Asked Answered
B

3

1

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 to conditional 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 there possible in angular2 ?

Backchat answered 1/5, 2017 at 11:35 Comment(0)
M
0
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

Mervinmerwin answered 1/5, 2017 at 11:40 Comment(0)
B
1

Günter Zöchbauer's solution is acceptable, doesn't affect the useage, let the component detect this, I also found a easier way to do this without any json by using the :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.

Backchat answered 1/5, 2017 at 11:50 Comment(0)
M
0
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

Mervinmerwin answered 1/5, 2017 at 11:40 Comment(0)
N
0

if you want to use conditional statement with *ngIf and else the yes it's 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

Nydia answered 1/5, 2017 at 11:43 Comment(1)
Can you explain how this helps?Annabel

© 2022 - 2024 — McMap. All rights reserved.