Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Input Directive Modifying Form Control Value

I have a simple Angular 2 directive that modifies the input value of a textbox. Note that i'm using the Model-Driven form approach.

@Directive({
  selector: '[appUpperCase]'
})
export class UpperCaseDirective{

  constructor(private el: ElementRef, private control : NgControl) {

  }

  @HostListener('input',['$event']) onEvent($event){
    console.log($event);
    let upper = this.el.nativeElement.value.toUpperCase();
    this.control.valueAccessor.writeValue(upper);

  }

}

The dom updates properly, however the model updates after every other keystroke. Take a look at the plnkr

like image 801
Mike Lunn Avatar asked Nov 18 '16 17:11

Mike Lunn


1 Answers

This thrills me because I encountered this earlier and was left scratching my head.

Revisiting the issue, what you need to do is to change your this.control.valueAccessor.writeValue(upper) where the ControlValueAccessor is explicitly writing to the DOM element and not to the control itself to instead call

 this.control.control.setValue(upper);

which will change the value on the control and be correctly reflected both on the page and in the control's property. https://angular.io/docs/ts/latest/api/forms/index/ControlValueAccessor-interface.html

A ControlValueAccessor abstracts the operations of writing a new value to a DOM element representing an input control.

Here's a forked plunker: http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview

like image 176
silentsod Avatar answered Oct 15 '22 05:10

silentsod