Binding to a selected field

In this recipe, we will show you how to bind a selected value from a <select> tag to a variable; so in effect, we now perform data binding from the UI to the code and have two-way data binding. We show a list of companies. You can find the code in the project pol_select.

How to do it...

  1. The script starts with webindex.html, where a component with the name pol-select is imported through the following line:
    <link rel="import"href="pol_select.html">

    From this, we know that the component is defined in pol_select.html, and the code behind it is in a file named pol_select.dart. For a discussion of the other tags, see the first recipe.

  2. The code for pol-select is defined in pol_select.dart:
    import'package:polymer/polymer.dart';
    
    @CustomTag('pol-select')
    classPolselect extends PolymerElement {
      final List companies = toObservable(['Google', 'Apple',   'Mozilla', 'Facebook']);
      @observable int selected = 2; // Make sure this is not null;   // set it to the default selection index.
    @observable String value = 'Mozilla';
    
      Polselect.created() : super.created();
    }
  3. The structure of the component is outlined in pol_select.html:
    <link rel="import"href="packages/polymer/polymer.html">
    <polymer-element name="pol-select">
    <template>
    <select selectedIndex="{{selected}}" value="{{value}}">
    <option template repeat="{{comp in companies}}"> {{comp}} </option>
    </select>
    <div>
    You selected company {{selected}} <br/>
    or from index:   {{companies[selected]}} <br/>
    or from binding: {{value}}
    </div>
    </template>
    <script type="application/dart" src="pol_select.dart"></script>
    </polymer-element>

The following screenshot is what you see when you run the app:

How to do it...

Binding with a select field

How it works...

Step 2 defines the list of companies to be shown. It also declares an index to be selected in List and value as a variable. Step 3 shows that to populate a <select> tag, the repeating template from the Binding and repeating over a list recipe in this chapter can be used. It also shows that the selectedIndex attribute is set from the code. When another company is selected, this also changes the values of selected and value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset