i have implemented a custom form control with custom validation but i can't manage to mark the control as invalid once the parent form is submitted i want that when user press submit the control gets invalidated.. so far it gets invalidated only when touching it.. in my onDoCheck i manage to read the form.isSubmitted property but i noticed that the control is still marked as "valid"
even if i build the logic and force it as invalid in my onDoChek.. that way in the parent component on submit i can't check for the control validity because i would set it after the onSubmit callback.. what am i missing here?
the ugly fix i can think of is adding
this.form.get('test').updateValueAndValidity();
this.form.get('test').markAsTouched();
on the onSubmit callback, but shouldn't it work out of the box without doing that?
here the stackblitz: https://stackblitz.com/edit/angular-k5un7v?file=src%2Fapp%2Fcustom-input%2Fcustom-input.component.ts
any help is greatly appreciated
Even my solution is not perfect I would suggest you to add NG_VALIDATORS in the
providers
of your component.Currently your form is
valid
when the application starts and it should not. In fact, if I run your example following properties are wronglytrue
:When I add NG_VALIDATORS in
providers
of your custom CVA component, these properties becomefalse
, as they should:Just adding these lines, your form and your custom field are now invalid when the app starts, since you already have added a
validate()
method in your component.Anyway the mat-error still doesn't show the error because of the Material component behaviors. From doc:
I don't know if you can easily change this behavior but now you can create your own styles and the form should properly work fine. Or, as other people told you, mark them as touched after submit.
I hope this advice can help you to find another way to fix your problem.
Here my StackBlitz: https://stackblitz.com/edit/angular-vgyug5?file=src%2Fapp%2Fapp.component.html