Saturday, December 12, 2020

How to render multiple templates in Lightning Web Components?

 In this blog post we will see "How to render multiple template in Lightning Web Components".

To understand this we will need to create multiple HTML files in the component bundle and than Import them all and add a condition in the render() method to return the correct template.

The returned value from the render() method must be a template reference.

How to render multiple template in Lightning Web Components

myComponent.html

<template>

   <p>

       I am default template.

   </p>

   <lightning-button label="Change Template" onclick={changeTemplate}></lightning-button>

</template>


myComponent.js

import { LightningElement } from 'lwc';

import myComponentOne from './myComponentOne.html';

import myComponentTwo from './myComponentTwo.html';

export default class MyComponent extends LightningElement {

mycomponentTemplate=true;

  render(){

    return this.mycomponentTemplate ? myComponentOne : myComponentTwo;

  }

  changeTemplate(){

      this.mycomponentTemplate=!this.mycomponentTemplate;

  }

}


myComponentOne.html

<template>

    <p>

        I am template one.

    </p>

    <lightning-button label="Change Template" onclick={changeTemplate}></lightning-button>

 </template>


myComponentTwo.html

<template>

    <p>

        I am template two.

    </p>

    <lightning-button label="Change Template" onclick={changeTemplate}></lightning-button>

</template>


testApp.app

<aura:application>

<c:myComponent></c:myComponent>

</aura:application>


OUTPUT:

render multiple templates lwc


How to render multiple template in Lightning Web Components

No comments:

Post a Comment