首页 > 解决方案 > 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 中得到了很好的声明:提供指令内容

标签: angularangular-reactive-formsangular-directiveangular-forms

解决方案


恕我直言,最快的解决方案是为可视化创建一个验证器并观察 FormControl 的 valueChanges:

form.get('inputName').valueChanges.subscribe(value=>{
    // Code from your onInput @HostListener
});

验证器将使用表单初始化:

this.form.group({ inputName: ['initialValue', yourValidator]});

推荐阅读