Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a form group to manage time of day as follows:

      time: new FormGroup({
        date: new FormControl(new Date()),
        startTime: new FormControl(null),
        startTimeMeridian: new FormControl(MERIDIAN.PM),
        stopTime: new FormControl(null),
        stopTimeMeridian: new FormControl(MERIDIAN.PM)
      }, [MyCustomValidators.futureDateTime()]),

Inside my futureDateTime() validator on the group I do some logic to validate the formGroup and if it's invalid I do the following:

control.get('startTime').setErrors(MY_CUSTOM_ERROR) // MY_CUSTOM_ERROR is a valid error object

or the same except on control.get('stopTime'). This works the FIRST time and appropriately sets the error on the FormControls when they first enter the invalid state. The second time though, they have empty error objects.

I set debug points to narrow down what's happening and my FormGroup validator is appropriately setting the error on the control again, but it looks like something within Angular's code is clearing the error object.

How can I set error objects on a control from a FormGroup validator?

EDIT:

I'm not sure what was removing my error, but I was able to change my error object structure to an Array of errors, and then set them on the FormGroup instead.

Instead of the formControls startTime or stopTime having errors, I now set them on the FormGroup and my UI will check for any relevant feedback inside the FormGroup's errors.

question from:https://stackoverflow.com/questions/65646215/angular-formgroup-validator-doesnt-preserve-seterror-on-formcontrol

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
574 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this!

control.get('startTime').setErrors(MY_CUSTOM_ERROR)
control.get('startTime').updateValueAndValidity() // Add this line to make sure its getting updated

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...