Miguel Moura
Miguel Moura

Reputation: 39434

Add server side errors to form in Angular

I have the following Angular 7 Component:

export class SendMessageComponent implements OnInit { 

  message: FormGroup;

  constructor(private formBuilder: FormBuilder, private messageService: MessageService) { }

  ngOnInit() {

    this.message = this.formBuilder.group({ 
      name: ['', Validators.required], 
      email: [''], 
      message: ['']
    });

  }

  onSubmit() {

    if (this.message.valid) {

      this.messageService.send(message).subscribe(

        (successResponse: SuccessResponse>) => { },

        (errorResponse) => {

          if (errorResponse.status === 400) {

            for (var error in errorResponse.error.errors) {

            }

          }            

        },

      );

    }

  }

}

When there are errors the server returns errorResponse.error.errors which is something like:

[
  { name: "Email", info: "Email is unavailable" }
]

I would like to add the server side errors to my form.

How can I do this?

Upvotes: 0

Views: 947

Answers (2)

prettyfly
prettyfly

Reputation: 3130

You can use setErrors() method on the form control you want to add the error to.

e.g, for your email field:

this.message.get('email').setErrors({ error: 'A server side error' });

Stackblitz example: https://stackblitz.com/edit/angular-hq4p43

For your use-case, you can do it your loop, so long as your server returns the same Name as your FormGroup controls.

for (let error in errorResponse.error.errors) {
   this.message.get(error.name.toLowerCase()).setErrors({ error: error.info });
}

More info: https://angular.io/api/forms/AbstractControl#setErrors

Upvotes: 4

Michal Cumpl
Michal Cumpl

Reputation: 1037

You can call FormControl's setErrors() method to achieve this.

https://angular.io/api/forms/AbstractControl#setErrors

Upvotes: 1

Related Questions