When validation fails, all fields are highlighted in the Div containing the FormGroup

In my Angular application, I need to utilize two fields - produced date and expiry date.

It is important to note that I must use <div [formGroup]...> since this component will be called within other forms. Using the form tag here is not an option.

Below is the implementation of MyFilter.component.ts:

export class MyFilterComponent {
  filterForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.filterForm = formBuilder.group({
      producedDate: ['', [Validators.required]],
      expiryDate: ['', [Validators.required]]
    });
  }
}

Additionally, here is the content of my-filter.component.html:

<div [formGroup]="filterForm">
    <div class="form-group">
        <label for="producedDate"> Produced Date</label>
        <input type="date" formControlName="producedDate" class="form-control">
        <div class="alert alert-danger" name="producedDateRequiredWarning"
            *ngIf="filterForm.get('producedDate').errors && filterForm.get('producedDate').touched">
            Field is Required.
        </div>
    </div>
    <div>
        <label for="expiryDate"> Expiry Date</label>
        <input type="date" formControlName="expiryDate" class="form-control">
        <div class="alert alert-danger" name="expiryDateRequiredWarning"
            *ngIf="filterForm.get('expiryDate').errors && filterForm.get('expiryDate').touched">
            Field is Required.
        </div>
    </div>
</div>

Currently, when a validation fails (e.g., the user touches the produced date field but does not input anything), the entire left border gets highlighted in red. Is there a way to resolve this without having to override the CSS?

https://i.sstatic.net/76rqK.png

Answer №1

Consider updating the ngIf condition to the following:

*ngIf="filterForm.get('manufacturedDate').touched && filterForm.get('manufacturedDate').hasError('required')"

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

Is it possible to develop a C equivalent of the typescript Record type?

Is there a way to create a record type equivalent in C like what can be done in TypeScript, and add attributes during runtime? I am aiming to replicate the following: const familyData: string[] = ["paul", "em", "matthias", "kevin"]; const myFamily: Record ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Yes, indeed - Entering the schema of a retrieved field from an Object schema

After deciding to upgrade from Yup version 0.29 to 1.2, I encountered some challenges with its types. Seeking assistance in finding the best solution for typing yup schemas. In version 0.29, the universal type Schema fit everywhere, but now it no longer d ...

What is the best way to hide the back arrow in Cordova UWP for Ionic 4?

I am currently developing a Windows 10 (UWP) application using Ionic 4 (Angular). I want to remove the back arrow from the interface: Example of back arrow I have attempted various solutions, such as implementing in the app.component constructor with in ...

What are the drawbacks of introducing a dependency within the constructor?

I'm struggling to understand why breaking the rules is considered bad. import {DepClass} from './di-import' // <- some dependency imports here class DI1 { dep1: DepClass constructor(){ this.dep1 = new DepClass() // ...

Encountering a problem while installing an Angular 2 npm package from an enterprise registry

We are utilizing an enterprise repository for NPM packages that mirrors the traditional registry "http://registry.npmjs.org/". I am currently attempting to fetch the following packages (listed in package.json) "@angular/common": "2.0.0-rc.4", "@angular/co ...

Executing a Click Action on a Button Using Protractor in AngularJS

Currently, I am in the process of automating a website using protractor. After coding a few steps, I encountered an error when trying to click on a button. The error message indicated that more than one element was found for the locator by.partialButtonT ...

Update the CSS variables in Angular Material version 15 to reflect new changes

Angular Material 15 introduces some significant changes to colors and spacing. As a result, I find myself needing to override the default CSS variable values in my styles.scss file. :root { --mdc-typography-button-letter-spacing: 'normal'; ...

Position Bootstrap Modal in the center horizontally

I am working on an Angular project and struggling to center my Bootstrap 3 Modal horizontally on the screen. Despite trying various solutions like using text-align: center and align = "center", I have been unsuccessful. Can someone guide me on how to prope ...

Using Material UI date picker with TypeScript: A Complete Guide

Well, I have to admit that I usually don't resort to putting 'any' as the type when I'm uncertain what to do, but right now, I'm starting to feel quite frustrated. I'm currently working with Material UI date picker in conjunct ...

typescript exploring the versatility of dynamic types and generics

Understanding TypeScript dynamic and generic types can be challenging for me. The goal is to create a function that generates an object with a specific type, where some properties of the object must match the parameters provided to the function. Essentia ...

Steps for accessing a particular item with *ngfor in Angular 2

I'm struggling to figure out why both elements of my array are displaying simultaneously in my browser instead of separately. Take a look at this screenshot to see what I mean: https://i.stack.imgur.com/0EKSn.png Is there a method to specifically ac ...

Safari 11.1 and Angular 9 - config object missing a defined key-value

While using Safari, I have encountered a problem in the Primeng input text field. When I type into the text box, errors are logged into the console. handleKeypress — injected.entry.js:8231TypeError: undefined is not an object (evaluating 'settin ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

"PrimeNG Dropdown: The 'Showclear' option reveals the clear icon right from

In my Angular 7 application, I've been utilizing PrimeNG's Dropdown component which has been performing well. Typically, I set the showClear property to true to display a small "x" button on the right side of the dropdown control. Clicking on thi ...

Perform an HTTP GET request to a RESTful service with specified parameters using Angular 2

I'm currently facing an issue while attempting to create a GET request to the YouTube Web API. I'm struggling with passing parameters through the http.get function and have confirmed the request is being sent using Fiddler. However, I keep receiv ...

Why does my array seem to update only once in the view?

I am currently working on a project that aims to visually represent sorting algorithms, but I have encountered an issue. In order to effectively visualize the sorting process of an algorithm, it is crucial to display every change in the array as the proc ...

Unable to halt the Observable interval

I've exhausted all possible solutions I could find, but I can't seem to stop the code inside the subscribe function of this interval. Could it be that I'm using the interval incorrectly? var subject = new Subject(); var interval = Observabl ...

Error encountered when transitioning to TypeScript: Unable to resolve '@/styles/globals.css'

While experimenting with the boilerplate template, I encountered an unusual issue when attempting to use TypeScript with the default NextJS configuration. The problem arose when changing the file extension from .js to .tsx / .tsx. Various versions of NextJ ...

Validation of forms using asynchronous requests in Magento

I've created a form in Magento using code, and it operates with ajax. Now I need to ensure that this form is validated properly. While I'd prefer to tap into Magento's validation features, I'm not sure how to trigger them without submi ...