Search code examples
angularangular-reactive-formsangular-directiveangular-forms

Angular 6.10.0 - @Directive and Reactive Forms


This is my @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);
    }
  }
}

On a 'normal' angular form <input> are restricted by my directive

<!-- Expected behaviour works perfectly -->
<form (ngSubmit)="submit()" #form=ngForm>
  <input myLabel type="text" ... >
</form>

But when it comes to ReactForms my directive isn't applied on the <input>

<!-- @Directive not applied -->
<div *ngSwitchDefault [formGroup]="myFormGroup">
  <input myLabel type="text" ... />
</div>

I couldn't find an answer on the web about How to apply a directive on a ReactForm?.
I know I should use a Validator but my @Directive already exists and creating two formatting rules will duplicate logic (how to format inputs) which doesn't seem clean...

EDIT: My Directive is well declared in app.module.ts
EDIT2: Provide directive content


Solution

  • The fastest solution imho would be create a validator for the visualization and observe the valueChanges of the FormControl:

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

    The validator would go with the form initialization:

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