Showing posts with label accordion in lightning web component. Show all posts
Showing posts with label accordion in lightning web component. Show all posts

Saturday, March 16, 2019

Accordion component Lightning web components(lwc)

This post explains how to create the accordion component in Lightning web components(lwc)

Demo
accordinLWCDemo.html
<template>
    <lightning-card title="Accordin Example">
        <template if:true={accounts}>
            <!-- accordion component with muliple sectio open -->
        <lightning-accordion allow-multiple-sections-open>
            <template for:each={accounts} for:item="acc" for:index="indexVar">
                <lightning-accordion-section key={acc.Id} name={acc.Name} label={acc.Name}>
                    <p><b>Id</b> : {acc.Id}</p>
                    <p><b>AccountNumber</b> : {acc.AccountNumber}</p>
                    <p><b>Phone</b> : {acc.Phone}</p>
                    <p><b>Industry</b> : {acc.Industry}</p>
                    <p><b>CreatedDate</b> : {acc.CreateDate}</p>
                    <p><b>Type</b> : {acc.Type}</p>
                    <p><b>Rating</b> : {acc.Rating}</p>
                </lightning-accordion-section>
            </template>
        </lightning-accordion>
        </template>
    </lightning-card>
</template>

accordinLWCDemo.js
import { LightningElement, track, wire } from 'lwc';
// importing apex class method to get the accounts
import retriveAccounts  from '@salesforce/apex/LWCExampleController.getAccounts';
// imported to show toast messages
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class AccordinLWCDemo extends LightningElement {
    @track accounts;

    // wire service to fetch the slesforce data
    @wire(retriveAccounts)
    wiredAccount({ error, data }) {
        if(data) {
            this.accounts = data;
            this.error = undefined;
        }
        else if(error) {
            this.error = error;
            this.accounts = undefined;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error!!',
                    message: error.message,
                    variant: 'error',
                }),
            );
        }
    }
}

accordinLWCDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="accordinLWCDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Result