angular - Angular 6.10.0 - @Directive 和响应式表单
问题描述
这是我的@Directive
/* Imports */
@Directive({
selector: '[ngModel][myLabel]'
})
export class MyDirective {
lastValue: string;
constructor(private myService: MyService) {}
@HostListener('input', ['$event']) onInput($event)
{
var start = $event.target.selectionStart;
var end = $event.target.selectionEnd;
$event.target.value = this.myService.format($event.target.value);
$event.target.setSelectionRange(start, end); // Preserve the cursor position
$event.preventDefault(); // A new event will be fired below
// Avoid infinite loop
if (!this.lastValue || (this.lastValue && $event.target.value.length > 0 && this.lastValue !== $event.target.value)) {
this.lastValue = $event.target.value;
// Must create a new "input" event since we have changed the value of the input, if not, there are no change detected in the value
const evt = document.createEvent('HTMLEvents');
evt.initEvent('input', false, true);
$event.target.dispatchEvent(evt);
}
}
}
<input>
我的指令限制了“正常”的角度形式
<!-- Expected behaviour works perfectly -->
<form (ngSubmit)="submit()" #form=ngForm>
<input myLabel type="text" ... >
</form>
但是当涉及到 ReactForms 我的指令并没有应用于<input>
<!-- @Directive not applied -->
<div *ngSwitchDefault [formGroup]="myFormGroup">
<input myLabel type="text" ... />
</div>
我在网上找不到关于如何在 ReactForm 上应用指令的答案?.
我知道我应该使用 aValidator
但我@Directive
已经存在并且创建两个格式化规则会重复逻辑(如何格式化输入),这看起来并不干净......
编辑:我的指令在app.module.ts
EDIT2 中得到了很好的声明:提供指令内容
解决方案
恕我直言,最快的解决方案是为可视化创建一个验证器并观察 FormControl 的 valueChanges:
form.get('inputName').valueChanges.subscribe(value=>{
// Code from your onInput @HostListener
});
验证器将使用表单初始化:
this.form.group({ inputName: ['initialValue', yourValidator]});
推荐阅读
- javascript - 使用 css 设置 Javascript 警报框样式
- google-bigquery - BigQuery - UDF 在视图中使用时返回 LEFT JOIN 错误
- laravel - 我的 laravel 应用程序最喜欢的功能
- python - Azure Data Lake + Python:身份验证失败
- elasticsearch - 有没有办法将数据(csv 数据)导入 winlogbeat kibana 仪表板?
- kubernetes - Kubernetes 上的超集与 Helm 不使用自定义值文件
- javascript - React native - 无效的正则表达式错误
- sql - 锁是否延伸到连接处?
- automation - 如何在将电子邮件发送给潜在客户但在旅程之间如果将潜在客户转换为联系人订户存在旅程时实施旅程
- java - Java long 转换为字节