Search code examples
javascriptpolymer

Send attribute to custom element on change


I am developing a web-app with Polymer. In my index.html I have 2 custom elements like follows

...
<body unresolved>
...
    <template is="dom-bind" id="app">
        <detail-card></detail-card>
        <information-card></information-card>
    </template>
...
</body>

Both custom elements are located in its own html file detail-card.html and infromation-card.html and then imported to the index file. What I am trying to do is to set a property on detail-card custom element and once it changes its value to execute a function on information-card custom element with the new value on the other side.

Basically I have 2 columns. detail-card shows a short version of the data of a purchase made by the user and the information-card shows the full data and specifications of the purchase. In both columns I have a set of buttons that change status (color) when pressed. I would like to change the color on both custom elements even when user only inputs in one of them. I was trying to do so by databinding a property and fire a function once it changes but I can't figure out how to sync both custom elements

Can anyone please help me to achieve this?


Solution

  • Basically to do what you ask you need a top level parent container, something like:

    <dom-module id="parent-card">
        <template>
            <detail-card prop-color="{{propColor}}"></detail-card>
            <information-card prop-color="{{propColor}}"></information-card>
        </template>
    </dom-module>
    <script>
        class ParentCard extends Polymer.Element {
            static get is() {
                return 'parent-card';
            }
            static get properties() {
                return {
                    propColor: {
                        type: String,
                        notify: false
                    }
                };
            }
        }
    
        window.customElements.define(ParentCard.is, ParentCard);
    </script>
    

    You should have another property propColor in both of 2 cards, when in one of the cards you change color maybe pressing the button, set the new value to propColor, that should trigger the change to the parent component ParentCard which will notify the second card.