Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to a Polymer element

Tags:

polymer

dart

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?

like image 416
Shailen Tuli Avatar asked Sep 10 '13 17:09

Shailen Tuli


1 Answers

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'.

like image 180
Shailen Tuli Avatar answered Sep 21 '22 08:09

Shailen Tuli