Skip to main content

Get Hands-on with Conditional Directives and Refs

Learning Objectives

After completing this unit, you’ll be able to:

  • Use the improved conditional directives.
  • Query DOM elements with refs.

Get Ready for the Hands-on Challenge

In this hands-on challenge, you’ll have an opportunity to modernize an existing Lightning web component while simplifying its code. You'll update its conditional directives to align with the latest best practices, and locate a DOM element without needing a selector.

Create a new Trailhead Playground now to follow along and try out the steps in this module. Scroll to the bottom of this page, click the playground name, and then select Create Playground. It typically takes 3–4 minutes for Salesforce to create your Trailhead Playground. 

Note

Yes, we really mean a brand-new Trailhead playground! If you use an existing org or playground, you can run into problems completing the challenges.

Launch the org you'll use for the hands-on challenge, then do the following.

  1. Create a Lightning web component.
    1. Name: child
    2. Replace the contents of child.js with the following code, which displays an alert using the LightningAlert base component, introduced in Summer ’22.
import { LightningElement, api } from "lwc";
import LightningAlert from "lightning/alert";
export default class Child extends LightningElement {
      @api
      async sayHi() {
            await LightningAlert.open({
                  message: "Hello Trailblazer!",
                  theme: "success",
                  label: "Greetings"
      });  
        console.log("Alert modal has been closed");
     }
}

2. Create a Lightning web component.

  1. Name: parent
  2. Replace the contents of parent.js with the following code which queries the Account object using Lightning Data Service.
import { LightningElement, api, wire } from "lwc";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import FIELD_NAME from "@salesforce/schema/Account.Name";
import FIELD_OWNER_NAME from "@salesforce/schema/Account.Owner.Name";
import FIELD_PHONE from "@salesforce/schema/Account.Phone";
import FIELD_INDUSTRY from "@salesforce/schema/Account.Industry";
export default class Parent extends LightningElement {
      @api recordId;
      @wire(getRecord, { recordId: "$recordId", fields: [FIELD_NAME, FIELD_INDUSTRY], optionalFields: [FIELD_PHONE, FIELD_OWNER_NAME] })
account;
      get name() {
            return getFieldValue(this.account.data, FIELD_NAME);
}
      get phone() {
            return getFieldValue(this.account.data, FIELD_PHONE);
}
      get industry() {
            return getFieldValue(this.account.data, FIELD_INDUSTRY);
}
      get owner() {
            return getFieldValue(this.account.data, FIELD_OWNER_NAME);
}
      sayHi() {
            let cmp = this.template.querySelector("c-child");
            cmp.sayHi();
     }
}

c. Replace the contents of parent.js-meta.xml with the following, which lets you use this component on an Account record detail page.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Account</object>
            </objects>
        </targetConfig>
   </targetConfigs>
</LightningComponentBundle>

d. Replace the contents of parent.html with the following, which conditionally displays either account information or an error message.

<template>
      <lightning-card title="Summer '23 Maintenance">
            <lightning-button slot="actions" label="Say Hi" onclick={sayHi}></lightning-button>
            <template if:true={account.data}>
                  <div class="slds-m-around_medium">
                        <p>Account Name: {name}</p>
                        <p>Industry: {industry}</p>
                        <p>Phone: {phone}</p>
                        <p>Owner: {owner}</p>
                 </div>
           </template>
           <template if:false={account.data}>
                <div class="slds-m-around_medium slds-text-color_destructive">An error occurred while retrieving data</div>
           </template>
           <c-child></c-child>
     </lightning-card>
</template>

3. Deploy the child and parent Lightning web components.

4. Add the parent component to the right column Account of the record detail page. Save and activate your custom page as the Org Default for the Desktop form factor.

5. Open an account and verify that it looks like the following.

Example of an Account with a Lightning web component.

Compartilhe seu feedback do Trailhead usando a Ajuda do Salesforce.

Queremos saber sobre sua experiência com o Trailhead. Agora você pode acessar o novo formulário de feedback, a qualquer momento, no site Ajuda do Salesforce.

Saiba mais Continue compartilhando feedback