It would be extremely handy to be able to do something along the lines of
const select = M.Select.init(el, options);
select.setValue('value'); // for single selects
select.setValue(['value1', 'value2']); // for multiselect
For as far as I can see there's no method available that does this.
Maybe it's interesting to implement this in the Dropdown component and then the Select component can simply forward it's calls to setValue to the dropdown.
I came across this problem when trying to implement a wrapper in Angular for Materialize.
In Angular for proper form integration you need to be able to set the value programatically at some point when a component wants to update it, which is currently not possible.
You can programmatically change the original select element, and then reinit the select plugin
What do you mean by reinit?
You can just init the plugin again, the same as always. All our plugins are built so that if you init a plugin multiple times, it will destroy the existing instance of the plugin and reinitialize the plugin.
const setMaterializeFormSelectValue = (id, value) => {
$(id).parent().find('.dropdown-content > li.selected').removeClass('selected').removeClass('active')
let liArr = $(id).parent().find('.dropdown-content > li')
let opArr = $(id).find('option')
// assumption: both arrays have the same index order
let text = '?'
opArr.each((i, op) => {
if ($(op).attr('value') === value) {
$(liArr[i]).addClass('selected').addClass('active')
text = $(liArr[i]).text()
}
})
// also apply the new text
$(id).parent().find('input[type=text]').val(text)
// also update thew hidden select
$(id).val(value)
}
setMaterializeFormSelectValue('#mySelect', 'some-option-value')