angular - Angular FormControl 值实际上是什么,为什么它与 nativeElement 值不同?
问题描述
更新:记录 blur 和 keyup 事件表明掩码永远不会进入 FormControl 值。这是为什么?即使在控件本身上调用 setValue() 方法也会去掉掩码。像:
<mat-form-field>
<mat-label>MSRP Pricing</mat-label>
<input
type="text"
#cost
matInput
mask="separator.2"
thousandSeparator=","
prefix="$ "
[formControl]="msrpCtrl"
(blur)="setVal(msrpCtrl, cost.value)"
(keyup)="log('keyup', msrpCtrl.value)">
<mat-error *ngIf="msrpCtrl.hasError('required')">
MSRP Price is required
</mat-error>
</mat-form-field>
setVal(control: FormControl, val){
console.log('set val as' + val);
control.setValue(val);
}
这仍然剥离了面具。这里有什么想法吗?
原帖:
我正在使用 Angular 8.0.0、Angular forms 8.0.0、Angular Material 8.2.3 和 ngx-mask 8.1.5
我一直在构建一个动态表单并使用掩码来帮助指导用户输入正确的数据。
不管出于何种原因,FormControl 值都会去掉掩码。示例案例 - 建议零售价成本。
所以我有一个简单的输入,如下所示:
<mat-form-field>
<mat-label>MSRP Pricing</mat-label>
<input
type="text"
#cost
matInput
mask="separator.2"
thousandSeparator=","
prefix="$ "
[formControl]="msrpCtrl">
<mat-error *ngIf="msrpCtrl.hasError('required')">
MSRP Price is required
</mat-error>
</mat-form-field>
当用户键入时,它会为每个千位分隔符添加一个逗号,只让他们指定 2 个小数点,并在第一个数字之前保留一个美元符号和一个空格。很简单,而且很有效。
当需要将数据实际发送到其他地方时,就会出现问题。如果用户在该字段中输入数字并且掩码显示的是
130,000.56 美元
formControl 值实际持有的是 130000.56
我希望它实际保存输入值 $ 130,000.56
我能弄清楚如何做到这一点的唯一方法是直接在我的 TS 文件中引用 DOM 输入元素,并以这种方式获取值:
@ViewChild('cost', {static: false}) cost: ElementRef;
.
.
.
console.log(this.cost.nativeElement.value);
// Or send the value on
这绝对不是理想的,尤其是对 40 多个输入进行此操作。首先从 FormControl 值中删除掩码是否有原因?如果没有,是否有更好的方法来捕捉面具显示的价值?
解决方案
我想在电话号码掩码中保留破折号时遇到了同样的问题。使用 Angular 8.2.12 和 ngx-mask 8.2.0 我通过将 dropSpecialCharacters 选项设置为 false 来解决它
<input type="text" formControlName="phone" mask="000-000-0000" [dropSpecialCharacters]="false" />
文档链接
推荐阅读
- php - 登录不起作用,但没有给出任何错误
- html - 如何创建淡入/淡出图像动画
- excel - 在 Excel“不可读的内容”中查找错误的公式
- wagtail - 将 HTML 查看添加到 Wagtail 上的 Draftail 编辑器
- python - Python - “字符串索引必须是整数”错误使用 json 和 twitter
- sql-server - 从 T-SQL 脚本中调用 T-SQL 命令的 *File*
- python-3.x - Bs4和python中的问题
- java - 将 MapboxMap 从一个活动发送到另一个活动
- database - 使用 TypeORM Cordova 数据库将图像保存为 Blob
- javascript - 仅在输入按钮的值发生更改后,使用 JavaScript 和 jQuery 更改警报框中的字符串