Having trouble with validating forms in Angular 4

Recently acquainted with Angular 4, I am currently working on integrating form validation messages in my application.

While the validation message displays as expected, I am facing an issue where the text field and label color do not change based on the state.

Here is the HTML code snippet I am using:

<form #AddressForm="ngForm" (ngSubmit)="SaveAddress(mAddress_Model)">
   <div class="form-group" [class.has-error]="Name.invalid && Name.touched" [class.has-success]="Name.valid">
   <label for="FName" class="control-label" >First Name *</label>
   <input type="text" required minlength="4" id="Name" name="Name" class="form-control "  [(ngModel)]="mAddress_Model.mFName"  #Name="ngModel">
    <div class="help-block alert-danger col-sm-12" *ngIf="Name.errors.required && Name.touched">
                    * First name is required
    </div>
  </div>
</form>

Despite using

**[class.has-error]="Name.invalid && Name.touched" [class.has-success]="Name.valid"**
, it does not seem to work for me, although the validation message div is functioning correctly.

I referred to a blog mentioned here:

I would appreciate any help or guidance on how to resolve this issue.

Answer №1

Perhaps this could be a suitable alternative:

[ngClass]="isErrorPresent ? 'new-class' : 'other-class'"

Answer №2

To customize the appearance of your input tag, you can adjust the border color using the [ngClass] attribute. This can be applied to both the input tag and the text within.

<input [ngClass]="{'decorate-red' : !mAddress_Model.mFName && flag, 'decorate-regular' : mAddress_Model.mFName && !flag}" type="text" required minlength="4" id="Name" name="Name" class="form-control "  [(ngModel)]="mAddress_Model.mFName"  #Name="ngModel">

To toggle the flag value based on errors, set it to false if there is an error, otherwise set it to true.

Add the following to your CSS:

.decorate-red {
   border: 1px solid red !important;
}

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

What is the best way to retrieve information from a mat-option loop?

Utilizing mat-select to fetch options from a database, the table also includes an images column. How can I change the image outside of mat-select when the mat-option is changed? I am attempting to extract the value outside of the mat-option loop. I have ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

javascript best practice for processing form data with arrays

As a newcomer to javascript, I've been exploring more efficient ways to handle certain situations. For example, would it be possible to utilize an array for this particular scenario? Here's the challenge: I have an HTML form with 6 fields that a ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

Angular2+ project missing important .vscode folder

Currently working on my Angular2+ project, I find myself in need of creating a launch.json file within the ~/.vscode directory. Unfortunately, it appears that the .vscode folder is missing from my Angular project folder. Although I am able to create the f ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

Running a TypeScript program that has been compiled with module resolution is not working as expected

I am currently in the process of compiling a TypeScript file with the following code: import { magic } from 'lib/magic'; magic(); The file structure looks like this: ./src/ main.ts lib/ a/magic.ts b/magic.ts Within ...

Sharing information between different pages in NEXT.js version 14

After performing a fetch and receiving a successful response containing data as an object, I use router.push to redirect the page to another one where I want to display the fetched data. const handleSubmit = async (event: any) => { event.preventDefa ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

Setting an Observable reference to null within a map operator does not have any impact

I am currently working on developing a generic DataService that includes hateoas implementation. Within this setup, there is a REST API endpoint called /root which provides all the required hateoas links. For instance, { _links : { login : { ...

Using TypeORM to establish a ManyToOne relationship with UUID data type for the keys, rather than using integers

I am currently facing a challenge in my Typescript Nestjs project using TypeORM with a PostgreSQL database. The issue arises when trying to define many-to-one relationships, as TypeORM insists on creating an ID field of type integer, while I prefer using U ...

Can you explain the significance of tslint's message: "Warning: The 'no-use-before-declare' rule necessitates type information"?

Can someone explain the significance of tslint's "no-use-before-declare" rule warning, which states that it requires type information? I've tried researching online but still don't fully understand its implications. ...

Angular: Exploring the Dynamic Loading of a Component from a String Declaration

Is there a way to compile a component defined by a string and have it render in a template while still being able to bind the click event handler? I attempted to use DomSanitizer: this.sanitizer.bypassSecurityTrustHtml(parsedLinksString); However, this a ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

Is the "Angular is not functioning" error message the result of a missing import?

Encountering an 'is not a function' error in Angular 7 / TypeScript 3, using an EventEmitter. This issue has been extensively discussed (a b), but solutions have not garnered many upvotes (a b c d e f). I am close to resolving it, but need s ...

The import of type cannot be done within paths in tsconfig

Currently, I am tackling a server side project utilizing TypeScript. In this context, I have established various types in ooo.d.ts and configured the paths within tsconfig.json. However, upon attempting to import the specified type, an error is being displ ...

How to bring in a class that was exported using `export = uuid` in Typescript

I'm facing a challenge while working with the node_module called uuid-js in TypeScript. After installing both the module and its typings, I am unsure how to properly import the module. Question: What is the correct way to import the module? The func ...

Learn how to incorporate slide transitions into the dropdown menu of a navbar in Bootstrap 4, complete with Vue.js transition effects

I'm attempting to incorporate a slide up and down transition into the bootstrap 4 dropdown menus using vue transitions. Unfortunately, the transition isn't functioning as expected. Even after utilizing the transition element, the animation stil ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Assessing functionality in Angular8 by testing a function that accesses an array from a service

I have a function that I want to test along with the current test setup: canShowIt() { let showit = false; const profils = this.requestsService.userProfil; showit = profils.some((profil) => profil.id === this.profileDetail.id); return showit; ...