1

I'm trying to change styles due to NgModel.control state. Since I wanna do it DRY, I thought that a directive reading component NgModel state will do the trick.

Is that even possible? Couldn't find any hints on how to do it.

My idea would so I can write something like this:

<div class="fields">
    <app-dummy-selector name="dummy" 
        [(ngModel)]="dummy" required appValidationError>
    </app-selector-moneda>
</div>

And then, my directive be defined with something like this

@Directive({
  selector: '[appValidationError]'
})
export class validationError {
  // do some logic to add Styles via Renderer2 or ElementRef
  // based on NgNodel control state 
  constructor(private el: ElementRef, private renderer: Renderer2) { }

}

To clarify UPDATE, what I ld like to avoid is to avoid adding #ctrl="ngModel" [ngClass]="{ error: (ctrl.invalid) && ctrl.touched }" like this:

<div class="fields">
    <app-dummy-selector name="dummy" 
        #ctrl="ngModel" [ngClass]="{ error: (ctrl.invalid) && ctrl.touched }" 
        [(ngModel)]="dummy" required appValidationError>
    </app-selector-moneda>
</div>
2
  • do u need to change the styles according to the ngModel value ? Commented Jan 11, 2018 at 16:24
  • I wanna change the style based on ngModel state not the value (I update the question providing more information) Commented Jan 11, 2018 at 16:33

1 Answer 1

1

You can inject NgControl on the host to access the control.

constructor(@Host() private ngControl: NgControl) { }

As for handling errors on the view which your questions seems to be about after your update, I can suggest the following two packages. (Full disclosure, they're mine.)

It's built to handle cases such as yours to reduce boilerplate.

Sign up to request clarification or add additional context in comments.

2 Comments

What about reacting to touch event? NgControl allow me to check for statusChanges but no touchChanges... :(
@genuinefafa There's no statusChanges on the control, no matter how you access the control. It simply doesn't exist yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.