Angular: a technique for creating customized error messages and modifying fields

When an error occurs in a form, the text fields are cleared and the errors are set as shown below

switch(result){
    case "SUCCESS":
        // handle success case
    case "ERROR1":
            this.Form.controls.text1.setValue('');
            this.Form.controls.text2.setValue('');
            this.Form.controls.text1.setErrors({ 'error1': true });
            break;
    case "ERROR2":
            this.Form.controls.text1.setValue('');
            this.Form.controls.text2.setValue('');
            this.Form.controls.text1.setErrors({ 'error2': true });
            break;
    case "ERROR3":
            this.Form.controls.text1.setValue('');
            this.Form.controls.text2.setValue('');
            this.Form.controls.text1.setErrors({ 'error3': true });
            break;
}

To avoid redundancy, a method was created as follows

setError(error : string){
    this.Form.controls.text1.setValue('');
    this.Form.controls.text2.setValue('');
    this.Form.controls.text1.setErrors({ error: true });
}

switch(result){

    case "SUCCESS":
        // handle success case
    case "ERROR1":
            setError('error1');
            break;
    case "ERROR2":
            setError('error2');
            break;
    case "ERROR3":
            setError('error3');
            break;
}

The fields are being cleared, but there is an issue with setting the errors. Any advice on how to correctly set a specific error as true?

Answer №1

It seems like you are looking to clear the fields and apply errors to your formControls based on your question.

If you need to set an error for a specific field, you can use the following code:

this.Form.get('controlName').setErrors({notValid: true});

To reset all fields in your form, you can simply call:

this.Form.reset();

Additionally, if you require custom validation for your form, you can check out the following link for guidance: https://alligator.io/angular/reactive-forms-custom-validator/

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

Steps for converting an Array of tuples into a Union of Tuples

I am attempting to develop a custom type that, when given an array of tuples as input, will generate the union of each index within the tuple. This may not be the most accurate terminology, but I hope you understand what I mean. const entries = [["name", ...

Tips for adding an extensive collection of fixed attributes to a function using Typescript

I am attempting to write a function that includes a lengthy list of static strings attached as properties, all returning the property as a string value: const arr = ["a", "b", "c"]; // there are around 140 items in the actual list const f = (tag: strin ...

Angular: cut down lengthy text with an ellipsis and display more upon click

I am currently working with Angular 8, Angular Material, and Bootstrap utilities. Below is the code snippet I have been using: <div class="p-1 text-break" *ngSwitchDefault [innerHTML]="cell.value | longText"& ...

Implementing a click event to convert text to input in Angular 5

I'm struggling with setting values instead of just getting them. I want to switch from using divs to input fields and update the values when in "editMode". <div class="geim__sets"> <div *ngFor="let set of game.sets" class="geim__set"> ...

Utilizing Nginx with Angular2 for a seamless PathLocationStrategy implementation in html5

Angular2 is a single-page site, so all URL requests need to be redirected to index.html using Nginx. Below is the Nginx server block configuration: server { listen 8901; server_name my_server_ip; root /projects/my_site/dist; location /.+& ...

Guide for integrating a locally cloned open source angular component into your Angular project

Currently, I have an Angular 10 project that includes an open source Angular component installed via the typical "npm install --s xxxxxxx" method. My goal is to duplicate the github repository of this open source Angular component onto my local ...

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

The 'type' property is not found on the 'never' type

There seems to be a typescript error showing up as Error: Property 'type' does not exist on type 'never' in the following code snippet: export const getSomething = (actionLog: [] | undefined) => { console.info(actionLog[length ...

Using CreateMany within a Prisma Create query

Hello, I have been working on implementing a create statement that accepts an array of another model. Below are my schemas: model House { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt property_name String ...

Navigating API data conversion on the frontend using Object-Oriented Programming

Currently, I am facing a challenge while developing the frontend of a web application using TypeScript. The dilemma revolves around efficiently converting a data object from an API response into a format suitable for the application. Let's consider r ...

Mocking a service dependency in Angular using Jest and Spectator during testing of a different

I am currently using: Angular CLI: 10.2.3 Node: 12.22.1 Everything is working fine with the project build and execution. I am now focusing on adding tests using Jest and Spectator. Specifically, I'm attempting to test a basic service where I can mo ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Tips for utilizing ng class within a loop

Having some trouble with my template that loops through a JSON file using json server. The issue I'm facing is related to correctly applying ng class when clicking on icons. Currently, when I click on an icon, it adds a SCSS class but applies it to al ...

The system encountered an issue while trying to access the property 'emailVerified' of an undefined object

I am currently working on retrieving the current user and attempting to assign the user values to a getter. In the constructor, I can see in the console that it is returning "email verified" as true. However, when trying to set it in the getter, I am enc ...

Issue with passing props to child component in React due to TypeScript error

In the process of developing an expense tracker app using react and typescript. expense_type.ts export type IState = { id : number, text : string, amount : number } export type IinitialStateType = { transactions : IState[] } expor ...

Using Vue.js 2 on multiple HTML pages with Typescript and ASP.Net Core

My ASP.Net Core MVC project utilizes VueJs2 for more complex tasks, with each view having its own corresponding js file. The directory structure is as follows: ├ Controllers\HomeController.cs (with actions Index & Details) ├ Scripts\Hom ...

When using Angular NGXS, calling `dispatch` method can lead to multiple

Currently, I am sending data from one component to be used in other components. However, I have noticed that when I dispatch the data, the subscribe function is being called multiple times. On a button click, I am dispatching the following: appStore.disp ...

Clarification Needed on Keyup Event in Angular 2

Within my application, I am dynamically adding a class based on certain conditions. When the user inputs something, I validate the value and then add the appropriate class accordingly. This functionality is functioning as expected. However, the class upda ...

Navigate to the parent element in the DOM

Looking to add some unique styling to just one of the many Mat dialog components in my project. It seems like modifying the parent element based on the child is trickier than expected, with attempts to access the DOM through the <mat-dialog-container> ...

Empowering user accessibility through intricate custom elements

In the world of web accessibility guidelines, labels are typically associated with form controls like <input> or <textarea>. But what happens when dealing with complex Angular / React / ... components that function as form controls? Picture a ...