I am currently writing an LWC OSS project and am currently confused about some reproducible side-effects on a <select>
. The element can be "injected" from outside, by setting the value of said element using javascript. I created this playground so you can experience it yourself:
Playground
The javascript loggs everything as expected. But the <select>
itself does not reflect the value, instead, it jumps to the first value very often.
I don't see any reason why this happens, at all.
html:
<template>
<button onclick={prev}>prev</button>
<select onchange={select}>
<option for:each={options}
for:item="option"
key={option.value}
value={option.value}
selected={option.selected}>
{option.value}
</option>
</select>
<button onclick={next}>next</button>
</template>
js:
import { LightningElement } from "lwc";
export default class App extends LightningElement {
selected = 'a';
values = ['a', 'b', 'c', 'd', 'e'];
get options() {
const selected = this.selected;
return this.values.map((option) =>
({
value: option,
get selected() {return this.value === selected}
}));
}
select(evt) {
console.log(evt.target.value);
this.selected = evt.target.value;
}
prev() {
let i = this.values.indexOf(this.selected);
console.log('current', this.selected);
if(i > 0) {
this.selected = this.values[--i];
console.log('prev', this.selected);
}
}
next() {
let i = this.values.indexOf(this.selected);
console.log('current', this.selected);
if(i >= 0 && ++i < this.values.length) {
this.selected = this.values[i];
console.log('next', this.selected);
}
}
}