Conditional markup in LWC
When we want to work with modal-ups and etc we will be using conditional markup in LWC to show and hide markup.
When we want to work with modal-ups and etc we might have to conditionally show and hide markup.
There are two ways by which we can do it.
- Using
<template if:true=''></template>
- Using this.template.querySelector() with adding and removing CSS classes.
Let's look at the first approach here, you will find a lot of examples that use the second approach on my blog (here is an example)
<template>
<!-- We are making sure there exists data before we iterate-->
<template if:true={records}>
<template for:each={records.data} for:item="record">
<p key={record.Id}>{record.Name}</p>
</template>
</template>
<template if:false={records.data}>
<p>OH OHH!! There exists no data!</p>
</template>
</template>
Here is the controller file that is responsible for getting the data back from an Apex method. It's basically wiring the output of the Apex method to a property, nothing fancy.
import { LightningElement, wire } from "lwc";
import allRecord from "@salesforce/apex/DatatableController.allRecords";
export default class DataTable extends LightningElement {
@wire(allRecord)
records;
}
Hope this is helpful!