Reputation: 713
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>
Upvotes: 1
Views: 409
Reputation: 19764
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.
Upvotes: 1