0

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?

2 Answers 2

4

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

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.