Search code examples
javascriptpolymerweb-component

Pass attribute to a component in Polymer


I'm trying to pass an attribute to a Polymer component in this way:

<sample-button is-connected="[[profileData.isConnected]]"></sample-button>

When profileData.isConnected=true I want to make property isConnected inside sample-button to be set to true in attached method. Why does it not change in Polymer? Should I fire event and call again the method to return profileData.isConnected?

And in my sample-button component:

<dom-module id="sample-button">
	<template>
      <another-button>
        Some text here
      </another-button>
	</template>
	<script>
      Polymer({
        is: 'sample-button',
        
        properties: {
          isConnected: {
            type: Boolean,
            value: false,
            observer: 'updateData'
          }
        },
        updateData: function (isConnected) {
          //some code here when isConnected has been changed
        },
        attached: function() {
          //I want to make isConnected set to true when attribute is-connected="true"
        }
      });
  </script>
</dom-module>


Solution

  • To make the 'isConnected' property of the sample button to follow the 'profileData.isConnected' of it's parent, I think the fastest way for you is to add a '$' at the end of your property name

    <sample-button is-connected$="[[profileData.isConnected]]"></sample-button>
    

    This is because in html a boolean html attribute is true if present and false if not (like hidden for example), so doing simply

    <sample-button is-connected="[[profileData.isConnected]]"></sample-button>
    

    make it present and always true.

    With the '$' polymer will add it only if true.

    With this your 'isConnected' property should be initialised with the good value, follow the changes of 'profileData.isConnected' in it's parent, and fire the observer in doing so.

    You don't need the 'attached' call back for that.