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

前端 未结 2 1607
清酒与你
清酒与你 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:54

    @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

提交回复
热议问题