LWC HTML:
<template>
<div class=”slds-p-around_medium lgc-bg”>
<div class=”slds-m-bottom_small”>
<lightning-button
label=”Collapse All”
onclick={clickToCollapseAll}>
</lightning-button>
<lightning-button
label=”Expand All”
onclick={clickToExpandAll}>
</lightning-button>
</div>
<lightning-tree-grid columns = {gridColumns}
data = {gridData}
key-field = “Id”
hide-checkbox-column = true
onrowaction={handleRowAction}>
</lightning-tree-grid>
</div>
</template>
LWC JS:
import { LightningElement, track, wire } from ‘lwc’;
import { NavigationMixin } from ‘lightning/navigation’;
import fetchAccounts from ‘@salesforce/apex/ExampleController.fetchAccounts’;
export default class Sample extends NavigationMixin( LightningElement ) {
@track gridColumns = [{
type: ‘text’,
fieldName: ‘Name’,
label: ‘Name’
},
{
type: ‘text’,
fieldName: ‘Industry’,
label: ‘Industry’
},
{
type: ‘text’,
fieldName: ‘FirstName’,
label: ‘FirstName’
},
{
type: ‘text’,
fieldName: ‘LastName’,
label: ‘LastName’
},
{
type: ‘button’,
typeAttributes: {
label: ‘View’
}
}];
@track gridData;
@wire(fetchAccounts)
accountTreeData({ error, data }) {
console.log( ‘Inside wire’ );
if ( data ) {
var tempData = JSON.parse( JSON.stringify( data ) );
console.log( ‘Data is ‘ + tempData );
/*var tempjson = JSON.parse( JSON.stringify( data ).split( ‘Contacts’ ).join( ‘_children’ ) );
console.log( ‘Temp JSON is ‘ + tempjson );*/
for ( var i = 0; i < tempData.length; i++ ) {
tempData[ i ]._children = tempData[ i ][ ‘Contacts’ ];
delete tempData[ i ].Contacts;
}
this.gridData = tempData;
} else if ( error ) {
if ( Array.isArray( error.body ) )
console.log( ‘Error is ‘ + error.body.map( e => e.message ).join( ‘, ‘ ) );
else if ( typeof error.body.message === ‘string’ )
console.log( ‘Error is ‘ + error.body.message );
}
}
clickToExpandAll( e ) {
const grid = this.template.querySelector( ‘lightning-tree-grid’ );
grid.expandAll();
}
clickToCollapseAll( e ) {
const grid = this.template.querySelector( ‘lightning-tree-grid’ );
grid.collapseAll();
}
handleRowAction( event ) {
const row = event.detail.row;
this[NavigationMixin.Navigate]({
type: ‘standard__recordPage’,
attributes: {
recordId: row.Id,
actionName: ‘view’
}
});
}
}
Apex Class:
public with sharing class ExampleController {
@AuraEnabled(cacheable=true)
public static List < Account > fetchAccounts() {
return [ SELECT Id, Name, Industry, ( SELECT Id, FirstName, LastName FROM Contacts ) FROM Account LIMIT 10 ];
}
}
Output: