0
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?

Salesforce LWCで入力値に応じた画面表示/非表示の実装方法

Last updated at Posted at 2024-10-03

目的

入力値に応じて、LWC(Lightning Web Component)の一部を表示または非表示にする実装方法について説明します。

例:input1input2を両方チェックすると、非表示文章を表示に変更します。

image.png

<template>
  <lightning-input
    type="checkbox"
    label="input1"
    name="checkbox1"
    checked={isInput1Checked}
    onchange={checkbox1Handler}
  ></lightning-input>
  <lightning-input
    type="checkbox"
    label="input2"
    name="checkbox2"
    checked={isInput2Checked}
    onchange={checkbox2Handler}
  ></lightning-input>
  <template lwc:if={isVisiable}>
    <p>状況により表示する</p>
  </template>
</template>

方法1(推奨しない):入力項目 setter で実装

input1input2 の setter を利用して、表示/非表示のフラグである isVisiable を設定します。

export default class SampleLWC extends LightningElement {
  _isInput1Checked = false;
  get isInput1Checked() {
    return this._isInput1Checked;
  }
  set isInput1Checked(value) {
    this._isInput1Checked = value;
    this.isVisiable = this.isInput1Checked && this.isInput2Checked;
  }

  _isInput2Checked = false;
  get isInput2Checked() {
    return this._isInput2Checked;
  }
  set isInput2Checked(value) {
    this._isInput2Checked = value;
    this.isVisiable = this.isInput1Checked && this.isInput2Checked;
  }

  isVisiable = false;

  checkbox1Handler(event) {
    this.isInput1Checked = event.target.checked;
  }
  checkbox2Handler(event) {
    this.isInput2Checked = event.target.checked;
  }
}

メリット

・直感的な実装方法です。
・必要なときに表示/非表示を切り替えるため、効率的です。

デメリット

・参照項目が増えるほどコードの管理や保守が難しくなります。
 極端な例として、100項目で表示/非表示を決定する場合、それぞれの項目ごとにロジックを実装する必要があります。

方法2(推奨):表示/非表示のフラグ getter で実装

getter を使って表示/非表示のロジックを実装します。これにより、isInput1CheckedisInput2Checked の変更に応じて、自動的に表示/非表示が画面に反映されます。

export default class SampleLWC extends LightningElement {
  isInput1Checked = false;
  isInput2Checked = false;

  get isVisiable() {
    return this.isInput1Checked && this.isInput2Checked;
  }

  checkbox1Handler(event) {
    this.isInput1Checked = event.target.checked;
  }
  checkbox2Handler(event) {
    this.isInput2Checked = event.target.checked;
  }
}

メリット

・コード管理が簡単
 表示/非表示のロジックを一箇所に集約しているため、コードの管理や保守が方法1より簡単です。

デメリット

・効率性
 複雑な画面では、getter が複数回呼ばれることがあり、理論上は方法1よりもパフォーマンスが劣る可能性があります。ただし、実際には表示速度にほとんど影響はありません。

0
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
0
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?