[英]How to format input with reactive form control in angular?
我有一个像下面这样的输入,与反应式表单控件绑定:
<mat-form-field appearance="fill" floatLabel="always" fxFlex>
<mat-label>My field</mat-label>
<input
matInput
#input="matInput"
[formControl]="amountControl"
[errorStateMatcher]="customMatcher"
/>
<mat-error *ngIf="amountControl?.invalid">{{ getErrorMessage$() | async }}</mat-error>
</mat-form-field>
现在,在用户输入值之后,需要格式化值,可能是模糊或自定义键盘快捷键,填充回html输入字段,并更新为带有格式化值的有界表单控件。
我正在考虑使用管道,但是,它似乎仅用于更改值的显示方式,但不能将其保存回支持formControl。
这样做的正确方法是什么?
我会这样做:
HTML:
<input
matInput
#input="matInput"
[formControl]="amountControl"
[errorStateMatcher]="customMatcher"
(blur) = "transform()"
/>
TS:
amountControl = new FormControl('');
transform(){
let transformValue = this.amountControl.value - 5; // your pipe here
this.amountControl.setValue(transformValue);
}
键入时您的值会发生变化,但在模糊时会发生变换,如果您希望值仅在模糊时更改,则可以使用:
amountControl = new FormControl('', {updateOn: 'blur'});
编辑: StackBlitz的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.