D
D
demidov5552020-07-08 11:51:47
Angular
demidov555, 2020-07-08 11:51:47

How to return the first custom validation value (NG_VALIDATOR) when using ngIf?

If you hang ngIf on a child component and NG_VALIDATOR (and NG_VALUE_ACCESSOR, respectively) will be used in this component, then the validate method will twitch as many times as we re-render the component.

The problem is that validate is called n times, and the parent control only accepts the first value.
Let's imagine a case if the child component is not valid and at the same time disappeared.
How to get around? Through the styles I think it's not cool.

https://stackblitz.com/edit/angular-ivy-pzqcgy

1) Click on the button 2 times (so that a non-valid input disappears and then appears)
2) Enter data into the input
2) result will no longer be true

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-07-08
@demidov555

It is necessary to clear the validators if the directive that imposes them is removed. It doesn't do it by itself.
This is generally sad, the validation of the control is performed by one function, and not by an array of functions. Several validators merge into one during their setup (under the hood it is called Validators.composewith the old validator and with the new one), so you cannot arbitrarily delete validators.
Well, the directive providing the validator in the same way cannot remove its validator from the control when it is ngOnDestroy.
Therefore, every time you render your component, its validator is added to all the others and will remain in memory even after the component is destroyed (and keep the seemingly deleted CVA in memory, this is a leak). The values ​​themselves will arrive in the new CVA, and the validator will still catch everyone.
here is an example how to fix https://stackblitz.com/edit/angular-ivy-va9xuk

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question