Skip to content
This repository was archived by the owner on May 20, 2023. It is now read-only.

Commit 4c65d85

Browse files
Googlernshahan
authored andcommitted
Add an option to have a material number input component format its contents on blur (like material money input's blurFormat).
PiperOrigin-RevId: 176870231
1 parent 45e7179 commit 4c65d85

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

lib/material_input/material_number_accessor.dart

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ const List<Type> materialNumberInputDirectives = const [
3737
///
3838
/// `keypressUpdate` attribute has the value update on every keypress while
3939
/// the default is the value only updating on a blur event.
40+
/// `blurFormat` attribute causes the input to be formatted on blur events.
4041
@Directive(selector: 'material-input[type=number],material-input[type=percent]')
4142
class MaterialNumberValueAccessor extends BaseMaterialInputValueAccessor
4243
implements ControlValueAccessor, OnDestroy {
@@ -50,7 +51,8 @@ class MaterialNumberValueAccessor extends BaseMaterialInputValueAccessor
5051
@Optional() NumberFormat numberFormat,
5152
@Attribute('changeUpdate') String changeUpdateAttr,
5253
@Attribute('keypressUpdate') String keypressUpdateAttr,
53-
@Attribute('checkInteger') String integer) {
54+
@Attribute('checkInteger') String integer,
55+
@Attribute('blurFormat') String blurFormat) {
5456
var updateStream;
5557
final changeUpdate = getBool(changeUpdateAttr ?? false);
5658
final keypressUpdate = getBool(keypressUpdateAttr ?? false);
@@ -65,13 +67,27 @@ class MaterialNumberValueAccessor extends BaseMaterialInputValueAccessor
6567
}
6668
numberFormat ??= new NumberFormat.decimalPattern();
6769
final checkInteger = getBool(integer ?? false);
68-
return new MaterialNumberValueAccessor._(
69-
updateStream, checkInteger, numberFormat, input, control);
70+
return new MaterialNumberValueAccessor._(updateStream, checkInteger,
71+
numberFormat, input, control, getBool(blurFormat ?? false));
7072
}
7173

72-
MaterialNumberValueAccessor._(this._updateStream, this._checkInteger,
73-
this._numberFormat, BaseMaterialInput input, NgControl control)
74-
: super(input, control);
74+
MaterialNumberValueAccessor._(
75+
this._updateStream,
76+
this._checkInteger,
77+
this._numberFormat,
78+
BaseMaterialInput input,
79+
NgControl control,
80+
bool blurFormat)
81+
: super(input, control) {
82+
if (blurFormat) {
83+
disposer.addStreamSubscription(input.onBlur.listen((_) {
84+
// If the value parses, it's a number so format it as such.
85+
if (_parseNumber(input.inputText) != null) {
86+
super.writeValue(_numberFormat.format(_parseNumber(input.inputText)));
87+
}
88+
}));
89+
}
90+
}
7591

7692
@override
7793
void writeValue(newValue) {

0 commit comments

Comments
 (0)