Reputation: 7245
I have a situation where I'd like to detect in a component whether an <ng-content>
element inside it's template gets populated with anything dynamically.
So consider this markup in a component
<div class="ald-layout__wrapper" [class.ald-layout__wrapper--has-side-panel]="sidebarPresent">
<!-- CONTENT SLOT -->
<ng-content select="ald-content"></ng-content>
<!-- SIDE PANEL SLOT -->
<ng-content select="ald-side-panel"></ng-content>
</div>
Example usage for this component usage:
<ald-layout>
<ald-content>
Content here...
</ald-content>
<ald-side-panel *ngIf="showSidePanel">
Side panel content
</ald-side-panel>
</ald-layout>
I want to be able to detect in the ald-layout
component when ald-side-panel
is present in the DOM.
I wondered about using a service to track the visibility\presence state of the side panel, but wondering if there is a better pattern\approach to use here?
Upvotes: 1
Views: 454
Reputation: 12367
If you use @ContentChildren
you'll get a property/collection of type QueryList
. You can listen for changes in the content children list by subscribing to it's changes property
Something like
@ContentChildren() cc: QueryList<Type>;
ngOnInit() {
this.cc.changes.subscribe(v => {
....
}
}
Upvotes: 1