2
votes

I have a very large form with a number of sections represented as separate Form Groups. At the end of each section I have a check button that checks the validity of all controls within that form group, so far it is as follows

checkValidity(g: FormGroup) {
    Object.keys(g.controls).forEach(key => {
      g.get(key).markAsDirty();
    });
    Object.keys(g.controls).forEach(key => {
      g.get(key).markAsTouched();
    });
  }

It works fine, but because my generic validator checks and processes validation messages on each controls' input blur event, the validation messages themselves don't pop up until after I focus and blur a control. So I would like to add something to my method above that triggers a blur event on each Form control in a form group, but I haven't been able to figure out how I would do that.

document.getElementById("myAnchor").blur(); from W3Schools shows how I can get element by id and trigger it's blur() that way. Using the method above, would I be able to access all elements in a FormGroup with a forEach to trigger blur on everything? (inputs, textareas, radio buttons and checkboxes)

Please le tme know.

1
You can try document.activeElement.blur() - yurzui
Is there a way I can traverse through all elements of a FormGroup and do so for each one in my above method? - David
Nope, FormGroup doesn't have references to elements. They are connected through bridge. There is one way is monkey patching - yurzui
How about traversing through the entirety of a document, and if the id/name of an input/textArea contains a substring or something, blur that input/textArea? Is such a thing possible? I am absolutely brutal at javascript/typescript. I'm learning this as I go along for a project at work. - David
Monkey patching? - David

1 Answers

3
votes

I just figured out a solution to this problem just now, and it didn't involve triggering blur or any DOM event. Having discovered updateValueAndValidity() for a previous problem, I called it on each control in the form group exactly the same way I marked all controls as dirty and touched in the question. Demonstrated below.

  checkValidity(g: FormGroup) {
Object.keys(g.controls).forEach(key => {
  g.get(key).markAsDirty();
});
Object.keys(g.controls).forEach(key => {
  g.get(key).markAsTouched();
});
Object.keys(g.controls).forEach(key => {
  g.get(key).updateValueAndValidity();
});
}

This properly displays the validation error messages under each control in the form group, where previously I would have to focus and then blur on any control for this to happen.