对于 Polymer 1.0.0 这对我来说很好用
创建一个可重用的行为,或者只是将convertToNumeric() 添加到您的 Polymer 元素中:
@HtmlImport('app_element.html')
library app_element;
import 'dart:html' as dom;
import 'package:web_components/web_components.dart' show HtmlImport;
import 'package:polymer/polymer.dart';
@behavior
abstract class InputConverterBehavior implements PolymerBase {
@reflectable
void convertToInt(dom.Event e, _) {
final input = (e.target as dom.NumberInputElement);
double value = input.valueAsNumber;
int intValue =
value == value.isInfinite || value.isNaN ? null : value.toInt();
notifyPath(input.attributes['notify-path'], intValue);
}
}
将行为应用于您的元素:
@PolymerRegister('app-element')
class AppElement extends PolymerElement with InputConverterBehavior {
AppElement.created() : super.created();
@property int intValue;
}
在元素的 HTML 中配置输入元素:
- 将
value绑定到您的属性:value="[[intValue]]",以便在属性更改时更新输入元素
- 设置事件通知以在值更改时调用转换器
on-input="convertToNumeric" notify-path="intValue",其中intValue 是要使用数值更新的属性的名称。
<!DOCTYPE html>
<dom-module id='app-element'>
<template>
<style>
input:invalid {
border: 3px solid red;
}
</style>
<input type="number" value="[[intValue]]"
on-input="convertToInt" notify-path="intValue">
<!-- a 2nd element just to demonstrate that 2-way-binding -->
<input type="number" value="[[intValue]]"
on-input="convertToInt" notify-path="intValue">
</template>
</dom-module>
另一种方法
创建一个属性作为getter/setter:
int _intValue;
@property int get intValue => _intValue;
@reflectable set intValue(value) => convertToInt(value, 'intValue');
创建一个行为或将函数直接添加到您的元素中
@behavior
abstract class InputConverterBehavior implements PolymerBase {
void convertToInt(value, String propertyPath) {
int result;
if (value == null) {
result = null;
} else if (value is String) {
double doubleValue = double.parse(value, (_) => double.NAN);
result =
doubleValue == doubleValue.isNaN ? null : doubleValue.toInt();
} else if (value is int) {
result = value;
} else if (value is double) {
result =
value == value.isInfinite || value.isNaN ? null : value.toInt();
}
set(propertyPath, result);
}
}
这样您可以使用与文本输入字段相同的标记
<input type="number" value="{{intValue::input}}">
或者如果你想延迟属性的更新,直到输入字段离开
<input type="number" value="{{intValue::change}}">