I am trying to focus an input element inside of a polymer template every time it stamps its contents. The problem is that I cannot select the input element until the template has loaded. Currently, I am just using setTimeout to focus the input 100ms after the template should load, but I want to know if there is a more elegant solution. Also, the autofocus attribute doesn't work, because the template may un-stamp and re-stamp many times. Right now, my code looks something like this (this is inside a polymer element definition):
Polymer({
// ...
showInput: false,
makeInputVisible: function() {
this.showInput = true;
var container = this.$.container;
setTimeout(function() {
container.querySelector("#input").focus();
}, 100);
},
});
<div id="container">
<template if="{{showInput}}">
<input id="input" is="core-input" committedValue="{{inputValue}}" />
</template>
</div>
But I would prefer something more like this:
Polymer({
// ...
showInput: false,
makeInputVisible: function() {
this.showInput = true;
},
focusInput: function() {
this.$.container.querySelector("#input").focus();
},
});
<div id="container">
<template if="{{showInput}}"
on-stamp="{{focusInput}}">
<input id="input" is="core-input" committedValue="{{inputValue}}" />
</template>
</div>
Any ideas are appreciated.
With Polymer 1.0, there is a 'dom-change' event fired by templates when they stamp. However, there is a significant performance cost to using dom-if templates since they need to manipulate the dom tree. It would be much better to do something like this:
<div id="container">
<input id="input" hidden="[[!showInput]]" value="{{inputValue::input}}">
</div>
observers: [
'_showInputChanged(showInput)',
],
_showInputChanged: function (showInput) {
if (showInput) {
this.$.input.focus();
}
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With