Angular 2 Input Directive Change Form Control Value

I have a simple Angular 2 directive that changes the input value of a text field. Note that I am using a form approach with a model.

@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 domain is updated correctly, but the model is updated after each keystroke. Take a look at plnkr

+6
source share
2 answers

This worries me because I have come across this before and left scratching my head.

Repeating the problem, you need to change this.control.valueAccessor.writeValue(upper) , where ControlValueAccessor explicitly writes the DOM element, not the control itself, instead calls

  this.control.control.setValue(upper); 

which changes the value on the control and is correctly reflected both on the page and in the control. https://angular.io/docs/ts/latest/api/forms/index/ControlValueAccessor-interface.html

A ControlValueAccessor abstracts the write operations of a new value to a DOM element that represents an input control.

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

+13
source

I was looking for something like this, but when I tried the code in my project, I got errors in the line this.el.nativeElement.value.toUpperCase () according to the working example above given by @silentsod.

I made changes to the code:

 let str:string = this.control.value; this.control.control.setValue(str.toUpperCase()); 

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

0
source

Source: https://habr.com/ru/post/1012462/


All Articles