Angular使用带有@HostListener的指令更新ReactiveForm的输入值是
我已经在ReactiveForm FormControl上放置了一个货币属性指令,该指令在输入事件(onKeyDown)上使用@HostListener来删除所有无效字符(字母和符号),因为它们被输入到输入中,但允许使用数字和小数.但是,如果在空输入字段中键入无效字符(即a)并且指令将其删除,则不会更新模型.
我使用货币指令添加了plunker设置.要了解我的问题,请遵循以下步骤: >输入123a你输入中没有a,因为不允许使用字母,并且因为表单无效而按钮被禁用(好) 您可以通过单击按钮并查看记录this.form.value的控制台来验证模型是否未更新,并显示{amount:’a’}.如果您接下来键入有效字符,则模型将仅包含该字符,并且已删除了该字符.因此,只有在这种情况下,模型才能正确更新. 这是AngularJS中使用ngModel验证器和解析器管道,modelValue,$setViewValue和$render()来轻松解决的问题,用于更新并强制AngularJS运行$digest.你是怎么做Angular的? 这是我的属性指令的片段,它成功地删除了不需要的字符: @HostListener('input',['$event']) onKeyDown(event: KeyboardEvent) { const input = event.target as HTMLInputElement; // Only numbers and decimals let trimmed = input.value.replace(/[^d.,]+/g,''); // Only a single decimal and choose the first one found if (trimmed.split('.').length > 2) { trimmed = trimmed.replace(/.([^.]*)$/,'$1'); } // Cannot start with decimal typed or pasted if (trimmed.indexOf('.') === 0) { trimmed = ''; } // AngularJS "like" solution would be something like: // ngModelCtrl.$setViewValue(trimmed); // ngModelCtrl.$render(); // Angular solution is??? input.value = trimmed; } 解决方法
所以我确实找到了一个使用NgControl的解决方案,我在其中注入了私有的ngControl:NgControl然后访问了它的控件属性this.ngControl.control.patchValue(newValue);,它在我的onKeyDown事件中更新了ReactiveForm中的输入字段模型 – 请参阅
plunker
但是基于智能和哑组件的使用,使用EventEmitter实际上是一个更好的解决方案,它将值从输入 – plunker传递给父表单(感谢Todd Motto和他的Ultimate Angular课程) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |