#How to show reactive form error using a switch?

15 messages · Page 1 of 1 (latest)

vestal swallow
#
export class FormContainerComponent implements OnInit {
  private rootFormGroup = inject(FormGroupDirective);

  @Input() formContainer!: FormContainer;

  public formGroup!: FormGroup;
  public errors?: ValidationErrors | null;

  ngOnInit() {
    this.formGroup = this.rootFormGroup.control;

    this.errors = this.formGroup
      .get(this.formContainer.formGroupName)
      ?.get(this.formContainer.formControlName)?.errors;

    console.log(this.errors);
  }

  public showError(): string {
    switch (this.errors) {
      case Validators.maxLength: {
        return 'max length error';
      }

      default: {
        return 'no error!';
      }
    }
  }
}

this.errors has a single error (maxLength). I want to use a function showError() to display the error in the template.

The switch is returning the "no error!" string, but "this.errors" has an error. Any suggestions what to fix?

#
  public showErrors(): string {
    if (this.errors) {
      if (this.errors.maxlength) {
        return 'Maxlength error'
      } else {
        return ''
      }
    } else {
      return ''
    }
  }

this seems to work but isn't the cleanest code

lavish abyss
#

you can use something like this in your template:

@if (<your-form-control>.hasError('<errorname>')) {
  <your-error-message>
}

example (if I didn't any mistakes):

const control = new FormControl('123456', Validators.maxLength(5));
<input [formcontrol]="control">
@if (control.hasError('maxlength')) {
  value is to long
}

https://angular.io/api/forms/AbstractControl#hasError
https://angular.io/api/forms/Validators#maxLength


Your code can be shortend to

public showErrors(): string {
  return this.errors?.maxlength
    ? 'Maxlength error'
    : '';
}
vestal swallow
#

the showErrors() function will of course handle more errors, and you're "just" moving the logic into the template. I rather have a function that renders the error for me.

lavish abyss
#

I use the error-mechanisms from the form-control for displaying the error. You can display multiple errors with more if-statements or the first error with a switch-statement.
I do not need to handle the error by myself anymore. I let angular do it for me.

vestal swallow
#

How is that different than from my approach by having a function return a error message based on the reactive formcontrol error value? Apologies if I come across snarky or obtuse. I'm just seeing the same code exept you do it in your template and I do it in the compoment

lavish abyss
#

I do not need to call "showErrors()" by myself somewhere.

vestal swallow
#

Yes I understand that, but like i said, i rather have my errors renderd in the component and just output in the template than to have that logic in the template. Alright, thanks for the input though 🙂

lavish abyss
#

And i do not need some error-fetching logic

this.errors = this.formGroup
  .get(this.formContainer.formGroupName)
  ?.get(this.formContainer.formControlName)?.errors;
vestal swallow
#

fair point

lavish abyss
#

If you want to fix your code, then you need to call the showError function. I do not see any call of this function. Maybe this helps:

ngAfterViewChecked(): void {
  this.showError();
}

https://angular.io/api/core/AfterViewChecked

vestal swallow
#

Oh sorry, the code works as expected. I get my error rendered in the DOM with the second snippit I shared

#

I want to use a switch statement in the showError function but I couldn't get it to "hit" the maxlength error. Using a if/else tree does work, but it not a clean approach

lavish abyss
#

or (never used it before, idk the right syntax)

ngOnChanges(changes: SimpleChanges): void
  if (changes.someValue.new !== changes.someValue.old) {
    this.showError();
  }
}
#

Ahh okay, I missunderstood it. Both are clean. The difference is, what you want to display the user. The switch-case will only display the first found error. The if-statement approach can display multiple errors.```typescript
switch (true) {
case this.control.hasError('maxLength'):
return "error 1";
case this.control.hasError('nextError'):
return "error 2";
default:
return "no error";
}
// -------------
let error = [];
if (this.control.hasError('maxLength')) error.push("error 1");
if (this.control.hasError('nextError')) error.push("error 2");
if (this.control.hasError('otherError')) error.push("error 3");
return error.join('; ');