Search code examples
angularcomponentsdetectionsectionsangular2-ngcontent

Angular2 check/detect ng-content select exist from parent node *ngIf statement


My question is about checking that <some_selector> connected with <ng-content select='some_selector'> was given or not in parent component. May be I give example for clarify:

We have parent component template (editor.html):

Here is my editor

<modal>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

And in modal component template (modal.html) we want to use such *ngIf statement:

<div class="modal>
    <div class="modal-body">
        <ng-content></ng-content>
    </div>
    <div class="modal-footer" *ngIf='hasNgContent("mfoot")' >
        <ng-content select="mfoot"></ng-content>
    </div>
</div>

We want to not show div.modal-footer if <mfoot> tag was nod used in editor template inside <modal> tag. So how to implement hasNgContent() method? or may be in angular2 there is more direct *ngIf statement that allow detect that <mfoot> tag was used in parent component tag or not.


Solution

  • You can do this with @ContentChildren and see the length of the collection. Something like:

    @ContentChildren(mfootComponent) children: QueryList<mfootComponent>;
    

    this will populate with all mfootComponents, so you can check whether you have any. I hope it helps.