1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【LWC】tree-grid

Last updated at Posted at 2021-08-26

tree-gridとは

レコードを一括で表示するにはdata-tableを使用することが多いですが、lwcにはtree-gridというものも存在します。
どちらもレコードを表示できますが、tree-gridは行を折りたたんだり展開したりできます。子レコードを表示するときなどに便利かもしれません。

image.png
このように取引先と取引先責任者をグループ化して表示することができます。
以下、今回の実装内容を載せるので参考にしてください。

レコードの取得

data-tableでは基本的に単一オブジェクトを取得しますが、tree-gridでは親-子リレーションで取得するのでデータの整形が必要になります。

SampleTreeGrid.js
import { LightningElement, api, wire } from 'lwc';
import getAccountWithContact from '@salesforce/apex/AccountTableViewController.getAccountWithContact';

export default class SampleTreeGrid extends LightningElement {
  columns = [
    { label: 'Account Name', fieldName: 'Name', type: 'text'},
    { label: 'Id', fieldName: 'Id', type: 'text'},
  ]
  
  accounts;

  connectedCallback() {
    getAccountWithContact()
    .then(data => {
      console.log('data');
      // オブジェクトをJSON文字列に変換
      let accountData = JSON.parse(JSON.stringify(data));
      for(let i = 0; i < accountData.length; i ++) {
        let cons = accountData[i]['Contacts'];
        if(cons) {
          accountData[i]._children = cons;
          delete accountData[i].Contacts;
        }
      }
      this.accounts = accountData;
      
    })
    .catch(error => 
      console.log(error))
  }
}

columnなどはdata-tableと同じ書き方ですね。データの取得の部分だけ若干複雑ですが一度形を理解してしまえば難しくはないです。
HTMLも載せておきます。

SampleTreeGrid.html
<template>
  <lightning-card title="取引先と取引先責任者" icon-name="custom:custom1">
    <div class="slds-p-around_medium">
      <lightning-tree-grid
        columns={columns}
        data={accounts}
        key-field="Id">
      </lightning-tree-grid>
    </div>
  </lightning-card>
</template>

datatableとの違い

おおまかな違いはありませんが、tree-gridではインライン編集が出来ません。その代わりに行拡張は出来るそうです。
もう少し調べる機会があったらまた書きます。

詳しく知りたい方はリファレンスをご覧ください。
tree-grid

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?