Is there a way to transfer attributes to a concealed custom polymer element that has been imported?

Yesterday, I was facing a challenge with custom Polymer elements:

<polymer-element name="my-custom-element" attributes="key" hidden>
  <script>
    Polymer({});
  </script>
</polymer-element>

I pondered over how to pass an attribute to my imported hidden custom Polymer element when importing it into another custom Polymer element like this:

<link rel="import" href="../my-custom-element/my-custom-element.html" key="15">

I questioned whether this is achievable. If not, what would be the right approach?

Answer №1

To successfully utilize your element, follow wirlez's guidance by importing the element's definition, creating an instance, and setting the key value as an attribute.

Here is an example:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>Polymer</title>
    <script src="http://www.polymer-project.org/components/webcomponentsjs/webcomponents.js"></script>
    <!-- import element definition from jsbin -->
    <link rel="import" href="http://jsbin.com/mojadu.html">
  </head>
  <body>
    <x-foo key="42"></x-foo>
  </body>
</html>

element definition

<!-- Ensure that your element imports Polymer as a dependency -->
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">

<polymer-element name="x-foo" attributes="key" hidden>
  <template>
    <h1>Hello from x-foo</h1>
    <h2>The key is {{key}}</h2>
  </template>
  <script>
    Polymer({
      keyChanged: function(oldVal, newVal) {
        console.log('the key is', newVal);
      }
    });
  </script>
</polymer-element>

You can view this example in action on jsbin here.

If you check the console, you will see the element logging the value for key.

If you intend to manipulate the element using JavaScript in index.html, it may be necessary to wait for the polymer-ready event before doing so.

For example:

document.addEventListener('polymer-ready', function() {
  var el = document.querySelector('x-foo');
  // Perform actions involving x-foo's key
});

Answer №2

In order to pass a custom attribute, you must utilize a custom element. The "link" tag itself is not considered a custom element. To create and incorporate your own custom elements into your web application, refer to this tutorial.

If you have not done so already, it's recommended to complete the entire tutorial for a better understanding.

Update: Just importing a custom element does not mean it is being used. After importing the custom element, be sure to use the tag with specific attributes like so:

<my-custom-element key="15"></my-custom-element>

Similarly to how core-ajax is utilized:

<core-ajax
    auto
    url="http://gdata.youtube.com/feeds/api/videos/"
    params='{"alt":"json", "q":"chrome"}'
    handleAs="json"
    on-core-response="{{handleResponse}}"></core-ajax>

It appears that you may want to implement it in this manner:

<link
    rel="import"
    href="../core-ajax/my-custom-element.html"
    auto
    url="http://gdata.youtube.com/feeds/api/videos/"
    params='{"alt":"json", "q":"chrome"}'
    handleAs="json"
    on-core-response="{{handleResponse}}"></link>

Unfortunately, this approach is not compatible with Polymer!

Answer №3

If we consider this as your polymer file:

<polymer-element name="my-custom-element" attributes="key" hidden>
      <script>
        Polymer({});
      </script>
    </polymer-element>

and here is the link importing the file in your html:

<link rel="import" href="../my-custom-element/my-custom-element.html" key="15">

There are a few approaches to achieve what you are asking for...

If you want to generate that value dynamically, then one way is to create a constructor for the custom element like this:

<polymer-element name="my-custom-element" constructor='MyCustomElement' attributes="key" hidden>
          <script>
            Polymer({});
          </script>
        </polymer-element>

Afterward, you can instantiate such an element within the code of the polymer element, for example:

var custom =  new MyCustomElement();

Insert this element into your DOM like so:

var dom = document.querySelector('otherElement'); //depends on scope
dom.appendChild(custom);
custom.setAttribute('attribute', value);

or
this.$.elementID.appendChild(custom);
custom.setAttribute('attribute', value);

I hope this aligns with what you need. Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular ng-bind-html directive allows you to bind HTML content to an

I am attempting to utilize $interpolate and ng-bind-html in order to bind the data from my scope variable to an html string as outlined in this solution. However, I have encountered an issue where the ng-bind-html result does not update when the value of m ...

Ways to incorporate a dynamic value into a chart created with chart.js?

I want to create a doughnut chart representing the number of individuals who have tested positive for Coronavirus and the number of deaths related to it. How can I transfer the same data from the top container into the chart? The confirmedCases and deaths ...

Ways to access states from a Vuex store within a Vuetify list in VueJs

Here is a snippet from my Vue file: import store from '@/store' export default{ name: 'myList', data: () => ({ show: true, listContent: [{ name: '1', icon: 'pers ...

What is the proper method for extracting solely pertinent JSON information from this particular web service?

I am in the process of integrating an external web service to incorporate remote data alongside my local data, pertaining to various events happening in the United Kingdom. These events will be fetched based on search parameters like name or date. The even ...

How can Angularjs code be properly enclosed within a closure?

My question revolves around a basic application that I have outlined: Angular scope not affecting ng-show as expected The issue at hand is that my application exposes global variables, which is far from ideal. I attempted to enclose the AngularJS code in ...

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

HTML code featuring multiple dropdown menus, each equipped with its own toggleable textarea

I have multiple HTML drop downs, each triggering a textarea based on the selection. Currently, I'm using show and hide JavaScript functions for each question individually. Is there a way to streamline this so that I don't have to write separate c ...

Centering Dynamic Text Vertically in Adobe Animate using Javascript

Adobe Animate CC Javascript Can someone share the correct way to vertically center text in a dynamic text box using Javascript within Adobe Animate? This is different from the typical CSS method of centering text vertically in HTML. The following code d ...

The deployment of the Fire-base Cloud Function was successful and error-free. However, the function does not appear to exist in the Firebase system

After deploying a JavaScript Cloud Function, it shows that the deployment is completed. However, when I check Firebase, the function is not there. Oddly, TypeScript Cloud Functions deploy successfully. I followed all the steps outlined in the original Fir ...

What alternatives can I consider to reduce the dependency on watchers in my controller?

Although it's not recommended to put a watcher inside a controller, in this particular case, how can I avoid using a watcher? Note: Using $rootscope is not an option. Here is the code: Plunker Edit - here's what I did: Plunker And here is th ...

Changing the opacity of the background when a Bootstrap modal is displayedHere's how you can

While working with a bootstrap modal, I noticed that the background content opacity does not change by default when the modal is open. I attempted to change this using JavaScript: function showModal() { document.getElementById("pageContent").style.opaci ...

Utilizing Vue JS methods to control a div element

Currently enrolled in an online coding course that utilizes a bot to check code for accuracy. The task at hand is to modify the following code... <div id="app"> <form @submit.prevent="onSubmit"> <input v-model="userName"> < ...

Ways to show dynamic text according to slider adjustments

I am struggling with adding an if condition to my form that includes a horizontal slider. My goal is to display text based on the position of the slider. Can someone offer some guidance on this, please? Here's my HTML code snippet: <form method=" ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

The onClick event for "history.go(0)" is functional in Internet Explorer, but it does not work in Mozilla Firefox. What can be done to address this problem specifically for Mozilla browser?

After experimenting with different browser compatibility, I have discovered a way to clear all fields when clicking the "New" button. By using the code onClick="history.go(0)", the fields are successfully emptied in IE but unfortunately fail in Mozilla. ...

What purpose does "Phaser.Display.Align.In.Center" serve when we already have the function `setOrigin` available?

I'm puzzled about the purpose of Phaser.Display.Align.In.Center. The code snippet below is taken from an official example class Example extends Phaser.Scene { constructor () { super(); } preload() { this.load.path = 'https:// ...

The ng-view in index.html is not being loaded by AngularJS

I've been working on setting up a single-page application using AngularJS. In my setup, I'm using Node with Express and have an Apache server functioning as middleware. The issue I'm facing is that while my index.html page loads without any ...

Verifying that users have chosen an option from a drop-down menu

I'm attempting to validate the selection made in the dropdown menu to ensure that the user has chosen a quiz. However, when I pick a different quiz from the list, the result shows as "1" and triggers an alert message. Strangely enough, it seems that t ...

Is it possible for jQuery to detect if an email was sent from the client's email account?

I am working towards a feature on my website where users fill out specific fields and then click "send email" to activate their email platform via "mailTo", with the email pre-populated for easy sending. The challenge lies in confirming if the user actuall ...

"How can I make a dropdown open and close when a button is clicked, but also close when clicking outside of it at the same

One button click opens a dropdown, and it also closes when clicked outside. toggleAllCategories() { this.setState({ isOpenAllCategories: !this.state.isOpenAllCategories }); } The issue arises when attempting to open and close the dropdown by clic ...