In this recipe, we show you how the data of a list can be displayed in a Polymer component. So we perform data binding from the code to the UI here as well as in the following recipe. You can find the code for this recipe in the project databinding_list
.
webindex.html
, where a component with the name pol-list
is imported through the line:<link rel="import"href="pol_list.html">
From this, we know that the component is defined in pol_list.html
, and the code behind it is in a file named pol_list.dart
. For a discussion of the other tags, see the previous recipe.
pol_list.dart
:import'dart:html'; import'package:polymer/polymer.dart'; @CustomTag('pol-list') classPollist extends PolymerElement { final List companies = toObservable(['Google', 'Apple', 'Microsoft', 'Facebook']); Pollist.created() : super.created() { companies.add('HP'), } addcompanies(Event e, var detail, Node target) { companies.add('IBM'), companies.add('Dell'), } }
pol_list.html
:<link rel="import"href="packages/polymer/polymer.html"> <polymer-element name="pol-list"> <template> <ul> <template repeat="{{comp in companies}}"> <li> {{comp}} is an excellent company to work for.</li> </template> </ul> <p><b>We selected {{companies.length}} companies for you. </b></p> <button on-click="{{addcompanies}}">Add some companies</button> </template> <script type="application/dart"src="pol_list.dart"></script> </polymer-element>
The following screenshot is what the web page displays when the app is run and the button is clicked:
We want to view the contents of the list on our page; this is made possible in step 2 by using the toObservable
function from the polymer
package. This function converts a literal List
to an ObservableList
(@observable
doesn't work for a list or map). However, the list is changed in the created event, which is called when the component is instantiated. Also, companies
is changed by pressing the button, which calls the method addcompanies
.
Step 3 shows how a template loop is created. The <template repeat="{{item in list}}"> content </template>
syntax means that for every item in the list the content inside the template (here, the <li>
tag) is rendered.
From the running app, as shown in the previous screenshot, we see that whenever the observed list is changed, these changes are reflected in the web page. It also shows that the data binding syntax {{ }}
can display properties of objects (here, length
of the list).