Lightning Web Component Composition

One component can be added within the body of another component. Composition allows you to create complex components/applications from simple building blocks.

To make the code more reusable and maintainable, it is beneficial to combine apps and components with a group of smaller components.

Let’s take a look at this simple conference app composed of 3 components:

  1. conferenceApp
  2. audienceList
  3. speakerList

conferenceApp

conferenceApp.html

<template>
<lightning-card title="Conference App" icon-name="standard:lightning_component">
<div class="slds-p-around_x-large">
<p class="header-para">Welcome to Salesforce Conference</p><br/>
<p><b>Speakers List</b></p>
<c-audience-list audiences={speakerslist}></c-audience-list>
<p><b>Audiences List</b></p>
<c-audience-list audiences={audienceslist}></c-audience-list>
</div>
</lightning-card>
</template>

conferenceApp.js

import { LightningElement } from 'lwc';
export default class ConferenceApp extends LightningElement {
audienceslist = [' 👤 John Doe ', ' 👤 Kunal Singh ', ' 👤 Jean Doe ', ' 👤 Mohan Singh ',' 👤 Mike ',' 👤 John Donaughy '];
speakerslist = [' 🎤 Marc Benioff', ' 🎤 Gaurav Singh', ' 🎤 Geeta Singh '];
}

conferenceApp.css

.header-para{
font-weight: bold;
font-family:cursive;
color: darkblue;
font-size: large;
}

speakerList

speakerList.html

<template>
<p style="color:red;">{speakers}</p>
</template>

speakerList.js

import { LightningElement ,api} from 'lwc';
export default class SpeakerList extends LightningElement {
@api speakers = [];
}
view raw speakerList.js hosted with ❤ by GitHub

audienceList

audienceList.html

<template>
<p style="color: green;">{audiences}</p>
</template>

audienceList.js

import { LightningElement ,api} from 'lwc';
export default class AudienceList extends LightningElement {
@api audiences = [];
}
view raw audienceList.js hosted with ❤ by GitHub

Advertisements

The component that owns the template is known as the owner. The c-conference-app component is the owner in this case. All of the assembled components are under the control of the owner.  The owner component can:

  • Set public properties on composed components
  • Call methods on composed components
  • Listen for any events fired by the composed components

Join 751 other followers
Advertisements
Advertisements