In this recipe, we will explore two polymer.dart
features:
<template if={{condition}}></template>
, where a condition is an expression involving observed or published variablesYou can find the code in the project custom_attrib
.
In this example, we simulate an oven, with the temperature as its attribute. We show the temperature in a textual form, and also test the temperature to display an appropriate message, as shown in the following screenshot:
webindex.html
, where a component with the name pol-oven
is imported through the following line:<link rel="import"href="pol_oven.html">
This component is used three times on the page:
<body> <pol-oven temperature="210"></pol-oven> <pol-oven temperature="500"></pol-oven> <pol-oven temperature="3000"></pol-oven> </body>
From this code, we know that the component is defined in pol_oven.html
, and the code behind it is in a file named pol_oven.dart
. For a discussion of the other tags, see the first recipe.
pol-oven
is defined in pol_oven.dart
:import'package:polymer/polymer.dart';
@CustomTag('pol-oven')
classPoloven extends PolymerElement {
@published int temperature = 0;
Poloven.created() : super.created() { }
}
pol_oven.html
:<link rel="import"href="packages/polymer/polymer.html"> <polymer-element name="pol-oven"> <template> <p>The oven is heated to {{temperature}} degrees Celsius. </p> <template if="{{temperature > 400}}"> <p>This is too hot. </p> </template> <template if="{{temperature > 1000}}"> <p>We will burn here. </p> </template> </template> <script type="application/dart" src="pol_oven.dart"></script> </polymer-element>
In step 1, we see that the same component, pol-oven,
can be used multiple times on the same page; each occurrence being a different instance of the component. Of course, a combination of different components is also possible, each time the component contains its attribute temperature
with a different value.
In step 2, it is shown that a custom attribute must be annotated with @published
; this means that it is not merely displayed (and updated when changed, indicated with @observable
), but is also an attribute to be used in the polymer
tag.
Finally, in step 3, we see that the attribute values are displayed, but also that a piece of the UI code is displayed whether the evaluated condition is true or false. If the attribute value changes in the code, the conditional templates are automatically re-evaluated, possibly changing the UI.