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

前端 未结 2 1606
清酒与你
清酒与你 2020-12-14 01:15

So I\'m trying to make a directive that can manipulate a FormControl.

It seems that if I use the long syntax for declaring form controls in the template instead, I c

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 01:52

    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

提交回复
热议问题