[SalesForce] Example of Lightning web Component with LWC container

Salesforce just only provided how to call the component in LWC container but no actual example. May anyone already implemented container, please provide the example.

Below example from salesforce guide link
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_components_compose

My question is can we define c-todo-wrapper component to call c-todo-item component.

<!-- todoApp.html -->
<template>
    <c-todo-wrapper>
        <c-todo-item item-name="Milk"></c-todo-item>
        <c-todo-item item-name="Bread"></c-todo-item>
    </c-todowrapper>
<template>

<!-- todoWrapper.html -->
<template>

        <c-todo-item item-name="Milk"></c-todo-item>
        <c-todo-item item-name="Bread"></c-todo-item>

<template>

<!-- todoItem.html -->
<template>
   Name {itemName}
<template>

Best Answer

In the example you have provided:

<!-- todoApp.html -->
<template>
    <c-todo-wrapper>
        <c-todo-item item-name="Milk"></c-todo-item>
        <c-todo-item item-name="Bread"></c-todo-item>
    </c-todowrapper>
<template>
  1. todoApp is the owner component of todo-wrapper and todo-item

  2. todo-wrapper is the container of todo-item but not owner.

My question is can we define c-todo-wrapper component to call c-todo-item component.

Yes. You have to use this.querySelector and this.addEventListener as todo-item is not owned by it.

For detailed example on the differences in the way you identify elements and add event listeners from owner or container components you can refer to LWC: Difference between "window" and "this"

ADDED BASED ON COMMENTS:

<!-- todoWrapper.html -->
<template>
    <div>
        <slot></slot>
    </div>
</template>

You can also use named slots in which case, you have to mention in which slot the components have to be injected. You can refer to https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_components_slots

Related Topic