polymerdom-if

Polymer 1.x: accessing element within dom-if


Here is my JSBin

Click on the "First Name: James" text.

I have an input element within dom-if. In an event, I am making dom-if to pass and so the element will come into existence but I cannot access the input element immediately after making the dom-if condition pass.

May be I need to know when the dom-if is actually evaluated and why the element does not exist even if the condition has become true.

<!doctype html>
<head>
  <meta charset="utf-8">
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import">
  <link href="iron-form/iron-form.html" rel="import">
  <link href="paper-input/paper-input.html" rel="import">
</head>
<body>

<dom-module id="x-element">

<template>
  <style></style>
  <template is="dom-if" if="{{!editMode}}">
    <span id="name" on-tap="_makeEditable">{{name}}: {{value}}</div>
  </template>
  <template is="dom-if" if="{{editMode}}">
    <paper-input id="input" label="{{name}}" value="{{value}}"></paper-input>
  </template>

</template>

<script>
  (function(){
    Polymer({
      is: "x-element",
      properties: {
        editMode: {
          type: Boolean,
          value: false
        },
        name: {
          type:String,
          value:"First Name"
        },
        value: {
          type:String,
          value:"James"
        }
      },
      _makeEditable: function() {
        this.editMode = true;
        //how to find the input element here
        //this.$$('#input').querySelector("input").focus();
        //this.$.input.querySelector("input").focus();
      }
    });
  })();
</script>

</dom-module>

<x-element></x-element>

</body>

Solution

  • This is because setting this.editMode to true does not update the DOM instantaneously.

    You should be running your selector asynchronously, so that Polymer has some time to update the DOM, such as:

    this.async(function() {
       this.$$('#input').focus();
    })
    

    Fiddle here.