Search code examples
javascriptpolymer

Polymer 2.0 call child event from parent


I keep running into bad examples or outdated 1.0 docs regarding calling child event from the parent in Polymer 2.0. Essentially all I want to accomplish is triggering a child event from the parent. But I also can not seem to find a reference in the tree structure of the parent element as well when call "this".

Index.html

<!DOCTYPE html>
<html>
<head>
    <link rel="import" href="/elements/parent-element.html">
</head>
<body>
    <parent-element></parent-element>
    <script src="js/polymer.js"></script>
</body>
</html>

parent-element.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="./child-element.html">
<dom-module id="parent-element">

  <template>
    <div>
      parent
      <child-element></child-element>
     </div>
  </template>

  <script>
    class ParentElement extends Polymer.Element {
        constructor(){
            super()

        }

      callChildEvent(){
        // call event
      }

        static get is() { 
            return "parent-element"; 
        }
    }
    customElements.define(ParentElement.is, ParentElement);
  </script>
</dom-module>

child-element.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="child-element">
  <template>
    <div on-click="customEvent">
        child element
    </div>
  </template>
  <script>
    class ChildElement extends Polymer.Element {
        constructor(){
            super()
        }

        childEvent(){
            console.log('event fired');
        }

        static get is() { 
            return "child-element"; 
        }
    }
    customElements.define(ChildElement.is, ChildElement);
  </script>
</dom-module>

Thanks for the help!


Solution

  • Give an id to

    <child-element id="childEl"></child-element>
    

    And fire child element function at parent like:

    this.$.childEl.childEvent();