Now, we'll take a look at two-way data binding, which usually goes hand-in-hand with forms.
In one-way data binding, we embedded the instance's property into the HTML template. The direction went only from the instance to the HTML.
But with form input fields, we can propagate its values from the HTML input to instance properties and back to HTML. In other words, you can change the instance's property by changing the input value, but you can also change the input value by changing the instance's property. This is why it's called two-way binding.
Better still, let's create an example. We'll create a page that includes the <my-form>
custom element:
<!-- web/index.html --> <html> <head> <script async src="packages/browser/dart.js"></script> <link rel="import" href="my-form.html"> </head> <body> <my-form></my-form> <script type="application/dart" src="main.dart"></script> </body> </html>
In this case, our custom element is a small form:
<!-- lib/my-form.html --> <link rel="import" href="../packages/polymer/polymer.html"> <polymer-element name="my-form"> <template> <form> <h3>input value {{inputValue}}</h3> <input type="range" value={{inputValue}}> <button type="button" on-click="{{set50}}">set 50</button> </form> </template> <script type="application/dart" src="my_form.dart"></script> </polymer-element>
Note that we're embedding inputValue
into two places and also binding an event called set50()
. Setting inputValue
as a parameter to the value
attribute means that every change to the input's value will propagate to the inputValue
property:
// lib/my_form.dart import 'dart:html'; import 'package:polymer/polymer.dart'; @CustomTag('my-form') class MyFormElement extends PolymerElement { @observable String inputValue = '0'; MyFormElement.created() : super.created(); void set50(Event e, var detail, Node target) { inputValue = '50'; } }
We are setting inputValue
by the <input>
element, but at the same time, you can change its value by clicking on the button. The question is, will pressing the button and setting inputValue
to 50
also change the input element? Yes, it will, because it's making use of two-way data binding.
We will use two-way data binding again in the next chapter with AngularDart.
3.137.217.220