0

I'm working on a form in Angular, and I need to determine if every invalid field has also been touched. This is to provide visual feedback to the user. I currently have a function that checks for invalid controls when the user changes a value, but I'm struggling to handle the case where a user simply touches the controls without changing their values.

getAllErrorsTouched(): boolean {
    return Object.keys(this.formUser.controls).every((key) => {
        const control = this.formUser.get(key);
        return control?.invalid ? control.touched : true;
    });
}

The issue is when I use this.formUser.statusChanges.subscribe(() => console.log(this.getAllErrorsTouched())). This only triggers when the user changes a value. If a user touches the fields without entering anything, the function doesn't trigger, even though the invalid fields have been touched

Is there a way to ensure that getAllErrorsTouched() is called whenever a user touches a field, regardless of whether they change its value? Any suggestions or best practices for implementing this functionality in Angular forms would be greatly appreciated!

1 Answer 1

0

The statusChange "emits an event every time the validation status of the control recalculates.", a simple focus/blur of an input not makes any validation.

You can use the (blur) method of the inputs, but in general, when we works using ReactiveForms, when submit you mark all the formsControls as touched to show the error if the form is not valid

<form [formGroup]="form" (submit)="submit(form)">
..
</form>

submit(form)
{
   if (!form.valid)
   {
     form.markAllAsTouched()
     return;
   }
   ..rest of actions you want..
   console.log(form.value)
}

For me has no much sense only show errors then touched

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to create a directive that automatically adds a blur/off-focus event to every input field. However, the problem I'm facing is that the input field is inside a component. This requires me to add the directive to the input field within the component as well. As a result, the directive gets applied to all input fields throughout my entire app, which is not an ideal solution for me. Adding the blur event and passing it to the every input-field by hand is also not ideal
@user3261212 Rememeber that you can use as selector [input] and the directive is applied to all the inputs that they are in a component that, if is a standalone one import the directive or, if are declared in a module, only if the module declare also the directive

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.