An easy guide to using validators to update the border color of form control names in Angular

I'm working on a form control and attempting to change the color when the field is invalid. I've experimented with various methods, but haven't had success so far. Here's what I've tried:

<input 
        formControlName="personNameField"
        type="text"
        placeholder="Please enter"
        [ngClass]="{'error': personNameField.errors}"
        ></input>
    

Here's how my TypeScript form control is set up:

form = this.builder.group({
    personNameField: new FormControl('',
      [Validators.required]),
  });

  getName(){
    this.form.get('personNameField')
  }

However, I keep encountering this error:

ERROR TypeError: Cannot read properties of undefined (reading 'errors')

Any insights into what might be going wrong?

UPDATE: I've added the getter and removed the question mark, but still, the bordering isn't working – only the error message is displayed.

Update2:

.error {
    // underline input field on error
    border: 1px solid red;
    display: block;
    color: red;
}

Desired Result: https://i.sstatic.net/QRNvK.png

Actual Outcome: https://i.sstatic.net/VprQA.png

Answer №1

Give this a shot.

[ngClass]="{'error': form.get('personNameField')?.errors}"

Answer №2

Validation of input using Bootstrap classes can be achieved easily by following these steps:

        <div class="form-group">
        <label for="title">title</label>
        <input id="title" type="text" formControlName="title" class="form- 
       control" [ngClass]="{'is-invalid': isCategorySubmitted && 
        categoryFormInfo.title.errors}" />
        </div>

To implement this in your TypeScript file:

isCategorySubmitted = false;

initFormBuilder() {
this.categoryForm = this.formBuilder.group({
  title: ['', Validators.required]
});

}

  get categoryFormInfo() {
return this.categoryForm.controls;

}

  submit() {
this.isCategorySubmitted = true;
if (this.categoryForm.invalid) {
  return;
}

  // Implement your logic after the submission

}

This method offers a simple approach to validate user inputs.

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

Issue with CSRF token validation in ASP.NET Core when integrating with Angular

To enhance the security of my application, I decided to implement CSRF-Token protection using Angular documentation as a guide. According to the Angular docs, if a cookie named XSRF-TOKEN is present in the Cookies, it will automatically be included in the ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Creating a worldwide object in JavaScript

I am trying to create a global object in JavaScript. Below is an example code snippet: function main() { window.example { sky: "clear", money: "green", dollars: 3000 } } However, I am unable to access the object outside th ...

Generating a Radio Button Label on-the-fly using Angular 8 with Typescript, HTML, and SCSS

Struggling with generating a radio button name dynamically? Looking to learn how to dynamically generate a radio button name in your HTML code? Check out the snippet below: <table> <td> <input type="radio" #radio [id]="inputId" ...

Tips for transferring form data from a React frontend to the backend Node.js server

I have been attempting to send FormData from React JS to my backend (Express Node server) with the code snippet provided below. However, I am encountering an issue where req.body.myFormData in expressTest.js is showing up as empty. Despite trying various ...

Immerse yourself in a world of virtual reality with the cutting-edge VR Vide

Currently, I am in the process of developing a virtual panoramic tour that features various panoramas linked together with hotspots. Each panorama contains a video hotspot that plays a video. However, I have encountered an issue where every time a new sce ...

Issue with bundling project arises post upgrading node version from v6.10 to v10.x

My project uses webpack 2 and awesome-typescript-loader for bundling in nodejs. Recently, I upgraded my node version from 6.10 to 10.16. However, after bundling the project, I encountered a Runtime.ImportModuleError: Error: Cannot find module 'config ...

Encountering issues when attempting to install vue-cli on a new project

After creating an empty project, I attempted to install vue-cli using the command npm install -g @vue/cli. However, during the installation process, I encountered the following errors and warnings from the interpreter: npm WARN read-shrinkwrap This versi ...

TypeScript: empty JSON response

I am encountering an issue with the JSON data being blank in the code below. The class is defined as follows: export class Account { public amount: string; public name: string; constructor(amount: string, name: string) { this.amount = amount; t ...

Comprehending the intricacies of routing within AngularJS

Question: I've been looking into this issue, but there seems to be conflicting answers. I created a simple example in Plunker to understand how routers work in AngularJS, but I'm having trouble getting it to function properly... Below is my inde ...

Linking two dropdowns in Ember with data binding

I need help with connecting two selectboxes. I want the options in the second one to be determined by what is selected in the first selectbox. I'm new to using Ember and could use some advice on how to approach this problem. I tried using computed pro ...

In Angular 2, templates may not be fully executed when utilizing ngAfterContentInit or ngAfterViewInit functions

When I try to access the DOM of the document, I notice that the template is only partially executed. Using a setTimeout helps me bypass the issue temporarily, but what is the correct way to handle this? import { Component, Input, AfterContentInit } from & ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Is it possible to update my services list based on which checkboxes I choose to uncheck at the top?

i am currently tackling a small project, and I have limited experience with javascript and json. Can someone assist me in resolving the final step? I am on the verge of completing it, but encountering some issues. My goal is to filter the results based on ...

I'm looking to create a Vuex getter to retrieve data from the Google API documentation – can you help

Can someone help me figure out how to create a getter in Vuex store with flat data from the Google Docs API? My goal is to extract the textRun content and store it in an array because there will be multiple messages. Currently, I have hard coded this respo ...

Performing an AJAX request inside of another AJAX request

I have integrated buttons into my website that are activated by JS AJAX loads. By clicking on these buttons, a JavaScript function is executed to load the contents of a PHP file into a specific div element. This setup is crucial as I want to avoid the enti ...

CSS footer element refuses to disappear

This sample application features a header, footer, and a content div that includes a table displaying various statistics of basketball players. One issue I encountered was with the footer when there were many entries in the table. This caused the footer t ...

Searching for a foolproof oauth framework that includes efficient refresh tokens

Currently, I am implementing oauth with refresh tokens for my Angular application and have a specific set of requirements: Automatically refresh the token when 5% of its time is remaining Handle situations where there is a loss of internet connection (re ...

Is there a way to format this into four columns within a single row while ensuring it is responsive?

I am working on a layout with a Grid and Card, aiming to have 4 columns in one row. However, the 4th column ends up in the 2nd row instead, as shown below: https://i.sstatic.net/gOeMm.png My goal is to align all 4 columns in a single row. Additionally, w ...

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...