Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Components, pass data to and from

My understanding is that data is passed to a custom html element via its attributes and sent out by dispatching a CustomEvent.

JavaScript objects can obviously be sent out in the event's detail field, but what if the element needs a lot of data passed into it. Is there a way to provide it with an object in JavaScript.

What if the element for instance contains a variable number of parts that needs to be initialized or changed dynamically (e.g. a table with a variable number of rows)? I can imagine setting and modifying an attribute consisting of a JSON string that is parsed inside the component, but it does not feel like an elegant way to proceed:

<my-element tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element> 

Or can you make the element listen to events from the outside that contains a payload of data?

like image 751
Johan Lundquist Avatar asked May 18 '18 06:05

Johan Lundquist


People also ask

How do I pass data into angular web component?

The first step to passing data into an Angular component is to create a custom property to bind to. This is done via “input” binding to pass data from one component to another (typically parent to child). This custom input binding is created via the @Input() decorator!

What is the purpose of a web page component?

Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.

Is svelte a web component?

Svelte is a great framework for building applications, but did you know you can create custom elements and web components with it? In this post, we'll learn how to create a Svelte component, export it as a custom element, and use it.


Video Answer


1 Answers

Passing Data In

If you really want/need to pass large amounts of data into your component then you can do it four different ways:

1) Use a property. This is the simplest since you just pass in the Object by giving the value to the element like this: el.data = myObj;

2) Use an attribute. Personally I hate this way of doing it this way, but some frameworks require data to be passed in through attributes. This is similar to how you show in your question. <my-el data="[{a:1},{a:2}....]"></my-el>. Be careful to follow the rules related to escaping attribute values. If you use this method you will need to use JSON.parse on your attribute and that may fail. It can also get very ugly in the HTML to have the massive amount of data showing in a attribute.

3 Pass it in through child elements. Think of the <select> element with the <option> child elements. You can use any element type as children and they don't even need to be real elements. In your connectedCallback function your code just grabs all of the children and convert the elements, their attributes or their content into the data your component needs.

4 Use Fetch. Provide a URL for your element to go get its own data. Think of <img src="imageUrl.png"/>. If your already has the data for your component then this might seem like a poor option. But the browser provides a cool feature of embedding data that is similar to option 2, above, but is handled automatically by the browser.

Here is an example of using embedded data in an image:

img {    height: 32px;    width: 32px;  }
<img src="data:image/svg+xml;charset=utf8,%3C?xml version='1.0' encoding='utf-8'?%3E%3Csvg version='1.1' xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' viewBox='0 0 314.7 314.7'%3E%3Cstyle type='text/css'%3E .st0{fill:transparent;stroke:%23231F20;stroke-width:12;} .st1{fill:%23231F20;stroke:%23231F20;stroke-width:10;stroke-linejoin:round;stroke-miterlimit:10;} %3C/style%3E%3Cg%3E%3Ccircle class='st0' cx='157.3' cy='157.3' r='150.4'/%3E%3Cpolygon class='st1' points='108,76.1 248.7,157.3 108,238.6'/%3E%3C/g%3E%3C/svg%3E">

And here is an example of using embedded data in a web component:

function readSrc(el, url) {      var fetchHeaders = new Headers({        Accept: 'application/json'      });        var fetchOptions = {        cache: 'default',        headers: fetchHeaders,        method: 'GET',        mode: 'cors'      };        return fetch(url, fetchOptions).then(        (resp) => {          if (resp.ok) {            return resp.json();          }          else {            return {              error: true,              status: resp.status            }          }        }      ).catch(        (err) => {          console.error(err);        }      );    }      class MyEl extends HTMLElement {      static get observedAttributes() {        return ['src'];      }        attributeChangedCallback(attrName, oldVal, newVal) {        if (oldVal !== newVal) {          this.innerHtml = '';          readSrc(this, newVal).then(            data => {              this.innerHTML = `<pre>  ${JSON.stringify(data,0,2)}              </pre>`;            }          );        }      }    }      // Define our web component    customElements.define('my-el', MyEl);
<!--  This component would go load its own data from "data.json"  <my-el src="data.json"></my-el>  <hr/>  The next component uses embedded data but still calls fetch as if it were a URL.  -->  <my-el src="data:json,[{&quot;a&quot;:9},{&quot;a&quot;:8},{&quot;a&quot;:7}]"></my-el>

You can do that same this using XHR, but if your browser supports Web Components then it probably supports fetch. And there are several good fetch polyfills if you really need one.

The best advantage to using option 4 is that you can get your data from a URL and you can directly embed your data. And this is exactly how most pre-defined HTML elements, like <img> work.

UPDATE

I did think of a 5th way to get JSON data into an object. That is by using a <template> tag within your component. This still required you to call JSON.parse but it can clean up your code because you don't need to escape the JSON as much.

class MyEl extends HTMLElement {    connectedCallback() {      var data;            try {        data = JSON.parse(this.children[0].content.textContent);      }            catch(ex) {        console.error(ex);      }        this.innerHTML = '';      var pre = document.createElement('pre');      pre.textContent = JSON.stringify(data,0,2);      this.appendChild(pre);    }  }    // Define our web component  customElements.define('my-el', MyEl);
<my-el>    <template>[{"a":1},{"b":"&lt;b>Hi!&lt;/b>"},{"c":"&lt;/template>"}]</template>  </my-el>

Passing Data Out

There are three ways to get data out of the component:

1) Read the value from a property. This is ideal since a property can be anything and would normally be in the format of the data you want. A property can return a string, an object, a number, etc.

2) Read an attribute. This requires the component to keep the attribute up to date and may not be optimal since all attributes are strings. So your user would need to know if they need to call JSON.parse on your value or not.

3) Events. This is probably the most important thing to add to a component. Events should trigger when state changes in the component. Events should trigger based on user interactions and just to alert the user that something has happened or that something is available. Traditionally you would include the relevant data in your event. This reduces the amount of code the user of your component needs to write. Yes, they can still read properties or attributes, but if your events include all relevant data then they probably won't need to do anything extra.

like image 107
Intervalia Avatar answered Sep 30 '22 21:09

Intervalia