5

When working with Web UI I could pass data to a component like this:

<my-element" name="{{someName}}"></my-element>

How do I pass data to a Polymer element?

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51

1 Answers1

7

You can pass data to a Polymer element, but there is a little bit more detail involved. Imagine the element with a single field, name:

// In element.dart.
import 'package:polymer/polymer.dart';

@CustomTag("my-element")
class MyElement extends PolymerElement with ObservableMixin {
   @observable String name;
}

And here is the accompanying html:

// In element.html.
<polymer-element name='my-element' attributes="name">
  <template>
    <h2>{{name}}</h2>
  </template>
  <script type="application/dart" src="element.dart"></script>
</polymer-element>

Note the attributes="name" part. That configures things so that the element can be passed the name attribute when it is created (you can pass in multiple attributes by separating them with a comma if your element needs it).

When creating the element, wrap it in a <template> tag that is bound to the values you want to pass to it:

// In index.html.
<template id='name1' bind>
  <my-element name="{{}}"></my-element>
</template>

<template id='name2' bind>
  <my-element name="{{}}"></my-element>
</template>

Each <template> gets bound to a separate value (we'll get to that in a second). When creating the element, you can get that value using {{}} syntax.

The data can be bound to the template in the following manner:

// In index.dart.
void main() {
  query('#name1').model ='Bob';
  query('#name2').model ='Rohan';
}

This way, the first <my-element> is created with the name 'Bob', and the second <my-element> is created with the name 'Rohan'.

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
  • With the current Polymer, shouldn't we be using `@piblished` instead of `@observable` on a property that corresponds to an externally settable attribute? – Sergey Shevchenko Jan 27 '14 at 22:29
  • Also, how do I assign to the model if my-element has multiple attributes? `querySelector('#name1').model = ['Rob', 34]` or `querySelector('#name1').model = {name: 'Rob', age: 34}` or...? – Sergey Shevchenko Jan 30 '14 at 22:31
  • And finally, what's the main advantage of using `template bind` as opposed to this: ``, and then in .dart: `(querySelector('#name1') as MyElement).name = 'Rob'`? Is it the fact that I don't have to import my_element.dart and downcast to MyElement? – Sergey Shevchenko Jan 30 '14 at 22:35