Conditional markup in LWC

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.

  1. Using <template if:true=''></template>
  2. 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>
dataTable.js

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;
}
dataTable.html

Hope this is helpful!