Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

Angular FormGroup validator doesn't preserve setError on FormControl

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

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

1 Reply

0 votes
by (71.8m points)

Try this!

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...