LoginSignup
0
0

More than 1 year has passed since last update.

テキストと選択リストの複合input

Posted at

選択リスト(comboBox)とテキスト入力(input)の融合です。
テキストも、選択リストどっちからでも入力できないかなと思って調べてみました。
どうやらlightning-inputでは無理そう?なので
HTMLにsldsのclassを割り当てて、それっぽくしましょう。

inputAndCombobox.html
<input id="input" name="input" list="valueList" class="slds-input" type="text">
<datalist id="valueList">
    <template for:each={values} for:item='item'>
        <option key={item.key} value={item.value}>{item.value}</option>
    </template>
</datalist>
inputAndCombobox.js
import { LightningElement, api } from 'lwc';

export default class inputAndCombobox extends LightningElement {
    const values = [
      { label: 'Option 1', value: 'option1' },
      { label: 'Option 2', value: 'option2' },
      { label: 'Option 3', value: 'option3' }
    ];
    initialized = false;
    
    renderedCallback() {
        if (this.initialized) {
            return;
        }
        this.initialized = true;
        // inputとdatalistを融合
        let listId = this.template.querySelector('datalist').id;
        this.template.querySelector("input").setAttribute("list", listId);
    }
}

こんな感じですね。
inputのclassに'slds-input'を割り当ててますが、レイアウトが少し気持ち悪かった気がします。
リストの中身の数にもよりますけど、ボタンからモーダル等で選択させた方が親切かな。
イレギュラー対応を取るんであれば、「その他」選択肢作って別途入力欄設ける方が無難ですかね。

気を付ける点としては
・親cmpの中にそのままinputやら書いてrenderedCallbackの処理を一緒にしちゃうと、うまくquerySelectorが動かないので子cmpとして呼び出す方が良いと思います。

今回は以上です。

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