Angular2 v.2.3 - Have a directive access a FormControl created through formControlName syntax

℡╲_俬逩灬. 提交于 2019-11-28 07:23:25

If you utilize NgControl, ElementRef, HostListener and constructor injection we can have a directive applicable to form controls from reactive forms in either formControlName or [formControl] guise and even template driven forms:

import { Directive, ElementRef, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[my-directive]'
})
export class MyDirective {
  constructor(private el: ElementRef, private control : NgControl) { }

  @HostListener('input',['$event']) onEvent($event){
    let valueToTransform = this.el.nativeElement.value;
    // do something with the valueToTransform
    this.control.control.setValue(valueToTransform);
  }
}

Here's an applicable demo

@silentsod answer would work flawlessly.

1. if you need to handle multiple events like key-press up/down or any other events, then you can go with below approach.
2. Also, it's better to define events in the directive itself.

import { Directive, ElementRef} from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[my-directive]',
  host: {
   '(input)':'onEvent($event)',
   '(keydown.backspace)': 'onEvent($event, true)'
})
export class MyDirective {
  constructor(private el: ElementRef, private control : NgControl) { }

  public onEvent($event, someEvent){
    let valueToTransform = this.el.nativeElement.value;
    // do something with the valueToTransform
    if(someEvent) {
    //do something 
    }
    this.control.control.setValue(valueToTransform);
  }
}

In the Html

<form [formGroup]="myForm">
<input type="text" id="myText" formControlName="myText" my-directive>
</form>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!