DRiFTy
DRiFTy

Reputation: 11369

How to access NgModel from directive in Angular 2+

I currently have a directive that I am placing on an <input> element that will format the text to uppercase, currency, ...etc. as the user types. This all works great by implementing ControlValueAccessor, but the control validity state is not updating after the writeValue method executes.

Is there a way to force the FormControl in the ngModel on the input to validate, or is there a way to inject the NgModel/FormControl instance into a directive that is placed on the same input? Whenever I try to inject it I get a cyclic dependency error. I'm trying to use the updateValueAndValidity() method on the control property of the NgModel instance to update the state, but this could be wrong as well.

If there is also a better way to approach this then I'm open to suggestions as well. Basically trying to translate a directive from Angular 1.x that used $formatters and $parsers and required the ngModel instance...

Let me know if you would like to see snippets of code for anything specific.

Upvotes: 2

Views: 1708

Answers (2)

DRiFTy
DRiFTy

Reputation: 11369

For anyone implementing a directive using ControlValueAccessor and having this same issue, I was able to get the validation state to update by calling the onTouched() method (the method that is set via the registerOnTouched() method) during the writeValue() method.

My directive updates the ElementRef.nativeElement.value property in writeValue() and then calls onChange() and onTouched() to get the value to propagate to the model, as well as update the validation state.

Upvotes: 0

j.k
j.k

Reputation: 463

Sounds like updateValueAndValidity is what you want.
Angular 2 AbstractControl class, which is the super for FormControl, has this method which will force the check of validity state on the control.

You could be accessing the specific formControl in a way that angular doesn't like. For reference, I have an overarching 'form' of type formGroup, a contained 'controlGroup' of type formGroup, and a specific 'control' of type formControl. I access its methods via form.controls['controlGroup'].controls.['control'].<method>

Upvotes: 1

Related Questions