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での入力項目の表示・非表示に応じた値の実装方法

Posted at

目的

入力項目の表示・非表示に応じた値の実装方法を紹介します。

要件

  1. 入力項目は表示の際、入力値を返す
  2. 入力項目は非表示の際、nullを返す
  3. 入力項目は非表示 → 表示に変更された際、最後の入力値を表示する

実装

HTMLファイル

以下はLWCのHTMLコード例です。

<template>
  <template lwc:if={isVisible}>
    <lightning-input
      type="text"
      label="テキスト入力"
      value={inputText}
      onchange={inputHandler}
    ></lightning-input>
  </template>
</template>

JSファイル

次に、LWCのJavaScriptコード例を示します。

export default class SampleLWC extends LightningElement {
  _inputText;

  // 入力値の取得
  get inputText() {
    return this.isVisible ? this._inputText : null;
  }

  // 入力値の設定
  set inputText(value) {
    this._inputText = value;
  }

  isVisible = false;

  // 入力イベントハンドラー
  inputHandler(event) {
    this.inputText = event.target.value;
  }
}

分析

各要件が達成されているか分析します。

1. 入力項目は表示の際、入力値を返す

  • isVisible = true の際、入力項目が表示され、_inputText に入力値を記録。
  • get inputText を呼び出すことで、_inputText の値を返します。

2. 入力項目は非表示の際、nullを返す

  • isVisible = false の際、入力項目が表示されず、ユーザーによる入力が不可。
  • get inputText() を呼び出すと、null を返します。

3. 入力項目は非表示 → 表示に変更された際、最後の入力値を表示する

  • isVisible = false → true に変更された際、記録された値 _inputText が入力項目に表示されます。
  • get inputText() を呼び出すと、記録された値 _inputText が返ります。
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?