3

I got in my Angular4 Project this small code:

<div class="divider"></div>

<ng-content select=".nav-toggle"></ng-content>

Now i want to make the divider only visible, if any content comes from outside in the ng-content tag. Is this possible? I absolutely cant find any informations about this.

Budi
  • 678
  • 2
  • 6
  • 27

1 Answers1

5

There is no good way to query for arbitrary projected content

@Component({
    selector: 'item',
    template: `
<div *ngIf="divider" class="divider"></div>
<div #wrapper><ng-content select=".nav-toggle"></ng-content></div>'})
class Item implements AfterContentInit {

    @ViewChild('wrapper') wrapper:ElementRef;

    divider:boolean = false;

    ngAfterContentInit() {
      console.log(this.wrapper.nativeElement.innerHTML); // or `wrapper.text`
      this.divider = !!this.wrapper.nativeElement.children;
    }
}

See also Access transcluded content

If you know the projected content is a specific Angular component or the element has a specific template variable applied, you can use @ContentChildren() (see also angular 2 / typescript : get hold of an element in the template).

n00dl3
  • 21,213
  • 7
  • 66
  • 76
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567