1

I'm working on a project that has different features for desktop and mobile devices. Some of these features can be replaced by slots. I'm trying to have one slot be able to be replaced by either a desktop slot named poster-foreground, or a mobile slot named mobile-poster-foreground, but default to poster-foreground if no mobile slot is applied (this is necessary due to current client implementations).

Currently I have it rendering the slot and changing its name upon render, based on whether its desktop or mobile, and based on the arbitrary variable mobilePosterSlotted, where mobilePosterSlotted is set to true if an attribute enable-mobile-poster-slot is set on the element (to not mess with current client implementations), like this:

private [$renderPosterIcon]() {
    let slotName = (this.mobilePosterSlotted && this[$isMobile]) ? "mobile-poster-foreground":"poster-foreground";
    let imageName = (this.mobilePosterSlotted && this[$isMobile]) ? "mobile-poster-foreground-image":"poster-foreground-image";

      return html`
        <slot name=${slotName} slot=${slotName} @slotchange=${this[$handleSlotChange]}>
           <figure class=${slotName} part=${slotName} slot=${slotName} >
             <img 
               class=${imageName}
               part=${imageName}
               src=${this.posterForeground} 
               alt="Clickable poster image to uncover 3D model viewer"/>
           </figure>
        </slot>
      `;
  }

where the renderPosterIcon function is called upon page load. I'd like it to be able to detect if the slot being used is either poster-foreground or mobile-poster-foreground before rendering the poster icon, and then render the slot name based on which of those slots is being used (without relying on an arbitrary variable/attribute being set), but I'm not sure if this is possible to do before rendering the element itself. Is there a different way I could go about this?

Cameron Crane
  • 113
  • 1
  • 12

1 Answers1

0

I figured out at least one solution.

This checks all children for a slot value of "mobile-poster-foreground", and if it exists, sets a boolean check to true. I put this before returning the html and it seems to work like a charm.

    let childElements = this.children;
    let mobilePosterSlotted;
    for(let child of childElements) {
      if(child.slot==="mobile-poster-foreground") mobilePosterSlotted = true;
    }

    let slotName = (mobilePosterSlotted && this[$isMobile]) ? "mobile-poster-foreground":"poster-foreground";
    let imageName = (mobilePosterSlotted && this[$isMobile]) ? "mobile-poster-foreground-image":"poster-foreground-image";  

    /* return html here*/ 
Cameron Crane
  • 113
  • 1
  • 12