Home > Blockchain >  Determine if ng-content selector matched anything
Determine if ng-content selector matched anything

Time:10-12

When using content projection with a selector, like so:

<ng-content select="[appChecklistTitle]">

How can I tell whether or not anything was matched? Basically I want an, "If content provided put it here, otherwise use some default content".

CodePudding user response:

I would suggest using the ng-template in such cases, by passing it from the parent, and handling it in the child as a ContentChild, then rendering it in the child's template using NgTemplateOutlet if it's presented, otherwise, rendering another default template.

You can do something like the following:

Child's component class:

@ContentChild('appChecklistTitle') appChecklistTitle: TemplateRef<any>; // You can use the preferred type instead of `any` here.

Child's component template:

<ng-container
  *ngIf="appChecklistTitle; else default"
  [ngTemplateOutlet]="appChecklistTitle"
></ng-container>
<ng-template #default>YOUR DEFAULT TEMPLATE HERE</ng-template>

Parent's component template:

<app-child>
  <ng-template #appChecklistTitle>CUSTOME TEMPLATE HERE</ng-template>
</app-child>
  • Related