Displaying errors from an API using Angular Material mat-error

I am currently working on a form that includes an email field. Upon saving the form, the onRegisterFormSubmit function is called. Within this function, I handle errors returned by the API - specifically setting errors in the email form control and retrieving error messages. In the HTML, I have logic to display error messages when the control has an error, but unfortunately, the message does not appear in case of an error.

export class MyErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
    }
}

matcher = new MyErrorStateMatcher();

this.registerForm = this.formBuilder.group({
  'email': ['', Validators.compose([Validators.required, emailValidator])]
});

public onRegisterFormSubmit(): void {
    if (this.registerForm.valid) {
        this.facade.register(); // save the form
        this.ngrxFormsFacade.errors$.subscribe(error => { // get errors from api
            if (error & error.email) {
                this.registerForm.controls.email.setErrors({ 'emailExist': true });
                this.errorEmailMsg = error.email;
            }
        })
    }
}

<mat-form-field appearance="outline" class="w-100 mt-1">
  <mat-label>Email</mat-label>
  <input matInput placeholder="Email" formControlName="email" [errorStateMatcher]="matcher" required>
  <mat-error *ngIf="registerForm.controls.email.hasError('emailExist')">{{errorEmailMsg}}</mat-error>
  <mat-error *ngIf="registerForm.controls.email.errors?.required">Email is required</mat-error>
  <mat-error *ngIf="registerForm.controls.email.hasError('invalidEmail')">Invalid email address</mat-error>
</mat-form-field>

Answer №1

Give this method a try and assign the error message to the emailExist key instead of using errorEmailMsg

this.registerForm.get('email').setErrors({ emailExist: error.email });

Then display it as shown below:

<mat-error *ngIf="registerForm.get('email').errors?.serverError">
              {{ registerForm.get('email').errors?.serverError }}
</mat-error>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding items to a Form Array in Angular

I am working on a project with dynamic checkboxes that retrieve data from an API. Below is the HTML file: <form [formGroup]="form" (ngSubmit)="submit()"> <label formArrayName="summons" *ngFor="let order of form.controls.summons.controls; let i ...

Personalize the appearance of autocomplete in Angular 2 using a dynamic <ng-content> tag

Currently, I am working on developing an autocomplete feature for a component. However, I am facing difficulties in handling the display of the items. I experimented with using ng-content to render the item but encountered failures. What I aim for is to ut ...

The error message "VueRouter does not have a property named 'history'" is common in Vue with TypeScript

In my typescript vue application, I encountered an error within a component while trying to access a parameter passed into the route. Here is the relevant code snippet: properties = getModule(PropertiesModule, this.$store); mounted() { id = this.$router. ...

Is it possible to utilize a const as both an object and a type within TypeScript?

In our code, we encountered a scenario where we had a class that needed to serve as both an object and an interface. The class had a cumbersome long name, so we decided to assign it to a constant. However, when we attempted to use this constant, we faced s ...

Steer clear of utilizing the "any" type in your Express.js application built with

I have a node/express/typescript method that looks like this: // eslint-disable-next-line export const errorConverter = (err: any, req: any, res: any, next: any) => { let error = err if (!(error instanceof ApiError)) { const statusCode = e ...

Utilizing Functions in Next.js with TypeScript: A Guide to Reusability

It is considered a best practice to separate data fetching functions into a folder named services, but I'm having trouble implementing this in my Next.js project. The function works when placed inside the component where I want to render the data, but ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

https://i.sstatic.net/0jyFI.png There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.u ...

"Mastering the art of debouncing in Angular using

I am facing an issue where, during a slow internet connection, users can press the save button multiple times resulting in saving multiple sets of data. This problem doesn't occur when working locally, but it does happen on our staging environment. E ...

Angular 5 is reporting a 404 Not Found error in response to the HTTP request to http://localhost:4200/api/

Starting my journey in Angular 5, I attempted to fetch a list of Cities from a JAX-RS API and encountered the following error : Http failure response for http://localhost:4200/api/: 404 Not Found Below are the files I am currently working with : ville ...

I am searching for answers to solve issues related to a JSON file

I am currently working on a tool that searches for matches in an input field by comparing the keywords entered by the user with a JSON. During my testing phase, I focused on using a single API that provides information about different countries and fortun ...

Trouble encountered while configuring and executing Electron combined with React, Typescript, and Webpack application

I am currently in the process of migrating my Electron application from ES6 to Typescript. Despite successfully building the dll and main configurations, I encounter a SyntaxError (Unexpected token ...) when attempting to run the application. The project c ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

Ionic threw an ERROR stating: TypeError - _co.toBoarding is not a function

While using Ionic 3/4, I encountered an error when trying to navigate between two components. This error has baffled me because everything was working fine with Ionic just three months ago. I am utilizing lazyload for component navigation. The specific er ...

Is it possible for us to integrate the Neo4j application's output into our Angular and NodeJS front-end?

Is there a way to integrate the Neo4j application output into my Angular Front-end application? I am open to using Nodejs for backend if necessary. Could you kindly provide guidance on how to specifically include just the middle section of a graph diagram ...

Using Next.js and Tailwind CSS to apply a consistent pseudo-random color class both on the server and client side

I am faced with a challenge on my website where I need to implement different background colors for various components throughout the site. The website is generated statically using Next.js and styled using Tailwind. Simply selecting a color using Math.ra ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

What is the best way to create buttons corresponding to the total number of "postId" properties in an array retrieved from an API call in Angular 10 using the "ngFor" directive?

export class AlphaComponent implements OnInit { apiData=[]; //array that stores API data constructor(private helpService:HelpService){ }; ngOnInit(){ this.fetchData() }; fetchData(){ this.helpService.getPostId().subscribe(( ...

Angular4's integration with AngularFireAuth for Google authentication is causing users to be redirected back to the source page before they can successfully

Previously, this feature was functioning perfectly. However, the current issue is that the browser is redirecting to a long URL and then quickly returning to the original source URL. This prevents users from logging into their Google accounts. authentica ...

Angular RxJS: The never-ending reduction

I have developed a component that contains two buttons (searchButton, lazyButton). The ngOnDestroy method is defined as follows: public ngOnDestroy() { this.unsubscribe$.next(); this.unsubscribe$.complete(); } I have created two observables from ...