Search code examples
spartacus-storefront

How I can get the slot name in which the component is rendered


I want to create a high order component which renders differently depending in which slot the component is. Is there any service where I can get the information in which slot the component is rendered?


Solution

  • You can inject the ancestor PageSlotComponent in your custom component and get the slot name by accessing its public property position$: Observable<string>:

    export class CustomComponent {
      constructor(@Optional() protected pageSlotComponent: PageSlotComponent) {}
      /*...*/
    
      slot$ = this.pageSlotComponent.position$;
    }
    

    Explanation:

    • In Angular you can inject the closest parent component of a given type, by passing it as a constructor dependency.
    • You might want to add @Optional() decorator if you plan to use your component outside the content slot (i.e. as a static component). It will help avoid crashing app in the runtime, but will just resolve PageSlotComponent instance safely to null.