5

In lit-element, in most of the cases passing data from parent-component to child-component via attributes and via properties result in the same thing.

I wonder in which case I should use attributes while which case properties?

zzzgoo
  • 1,974
  • 2
  • 17
  • 34

1 Answers1

6

The difference between attributes and properties is that attributes are expressed in the DOM, while properties are not. The element can decide to reflect the properties back to attributes, but that is somewhat orthogonal. Example:

<my-button raised></my-button>

Here, raised is a boolean attribute, and it is convenient to pass data that way because you can do it declaratively in the DOM. <my-button>'s implementation does not have to know whether the attribute or the property was used to pass this data, because attributes get converted to properties automatically (if a property with a matching name was declared).

The following works as well (lit-element specific), but assigns the property directly.

<my-button .raised=true></my-button>

The implementation of my-button can decide if changes to the property get reflected back to the attribute. This is useful if you want to use the attribute, for example, in CSS for styling.

Generally, however, you just assign properties and let the custom element decide whether the property gets reflected back to the attribute. Say you want to control the button programmatically, you would just assign the property

this.button_.raised = true;

instead of writing

this.button_.setAttribute('raised', true);

Note, this always works with custom elements and even a few native elements (e.g., input's value is a property, too). But you can't write:

this.myDiv_.id = 'container';

because <div>s don't have properties, and you have to use setAttribute().

crazypeter
  • 1,279
  • 1
  • 10
  • 14
  • a conclusion for your post: use properties in prefer. – zzzgoo Aug 20 '19 at 06:27
  • any way, I don't think it's a perfect design. In a team, maybe someone always use properties while some others always use attributes, it will end with mess. – zzzgoo Aug 20 '19 at 15:13