Polymer dart: Data bind integer value to String attribute

后端 未结 2 1647
甜味超标
甜味超标 2020-12-22 00:53

I am trying to bind an integer to a String attribute. To say exactly, I am trying to bind a published integer variable to the value attribute of the text input element.

2条回答
  •  时光说笑
    2020-12-22 01:12

    This is for Polymer <= 0.16. For Polymer >= 1.0 see my other answer.

    HTML attributes store only string values. What you could do is to use a getter/setter for binding and parse when the value is set.

    @observable
    int data;
    
    @ComputedProperty('data') // haven't tried this but should work - see comments on http://japhr.blogspot.co.at/2014/08/whats-difference-between-attribute-and.html
    @observable
    get dataValue => data;
    set dataValue(val) {
      if(val == null) {
        data = 0;
      } else if(val is num) {
        data = val.toInt();
      } else if(val is String) {
        data = num.parse(val, (v) => 0).toInt();
      } else {
        data = 0;
      }
    }
    

    or use a transformer or custom Polymer expressions
    like explained in polymer dart input binding int properties

    Alternative approache uses Dart Polymer 1.0 (also possible with Dart Polymer 0.16)

    app_element.dart

    @HtmlImport('app_element.html')
    library _template.web.app_element;
    
    import 'dart:html' as dom;
    import 'package:web_components/web_components.dart' show HtmlImport;
    import 'package:polymer/polymer.dart';
    
    @PolymerRegister('app-element')
    class AppElement extends PolymerElement {
      AppElement.created() : super.created();
    
      @property int intValue;
      @property String stringValue;
    
      @reflectable
      valueInputHandler(dom.Event event, [_]) {
        var input = (event.target as dom.NumberInputElement);
        var value = input.valueAsNumber;
        if (!value.isNaN && !value.isInfinite) {
          set('intValue', value.toInt());
          input.setCustomValidity('');
        } else {
          // just to get the `:invalid` pseudo-class for styling
          input.setCustomValidity('Not a number.');
        }
      }
    }
    

    app_element.html

    
    
      
    
    

提交回复
热议问题