Issue with Validators in Model-driven Forms

Currently conducting testing on a basic application. These are the files in use:

home.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

@Component({
    selector: 'app-home',
    templateUrl: 'home.component.html'
})
export class HomeComponent {
    form: FormGroup;

    constructor(fb: FormBuilder) {
        this.form = new FormGroup({
            'firstName': new FormControl('', Validators.required),
            'password': new FormControl('', Validators.minLength(5))
        });
    }
    
    onSubmit() {
        console.log('model-based form submitted');
        console.log(this.form);
    }
}

Accompanying the above is the template file:

<section class="sample-app-content">
    <h1>Model-based Form Example:</h1>
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <div class="form-field">
            <label>First Name:</label>
            <input type="text" formControlName="firstName">
        </div>
   <div class="form-field">
        <label>Password:</label>
        <input type="text" formControlName="password">
   </div>
    <p>
        <button type="submit" [disabled]="!form.valid">Submit</button>
    </p>
</form>

The issue lies in the correct recognition of Validators, evidenced by enabling the submit button when typing "firstname", but failing to turn the input field red upon leaving it empty.

In light of this, what misstep have I made?

UPDATE:

A live demonstration can be accessed via link below

http://plnkr.co/edit/cs6N0n?p=preview

Answer №1

When it comes to Angular validation, the `ng-invalid` css class is vital for indicating failed validations. However, if you don't have `ng-invalid` defined in your CSS, you won't see a red border.

To make it work, you can define the style in your CSS like this:

.ng-invalid {
  border-color: #ff0000;
}

It's puzzling why the minLength(5) validator allows an empty password. This could be either an angular bug or intentional behavior that requires combining it with the required 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

Combining two observable entities

Utilizing Angular 4 and rxjs, the objective is to fetch data from two distinct servers in JSON format, merge this data, and exhibit it in a list by associating the list with an observable array. **Word Search Component TypeScript File:** @Component( ...

Error: Unable to use import statement outside of a module when deploying Firebase with TypeScript

Every time I try to run firebase deploy, an error pops up while parsing my function triggers. It specifically points to this line of code: import * as functions from 'firebase-functions'; at the beginning of my file. This is a new problem for me ...

AngularDart's runtimeType object

My component is designed to accept a model object, but the type of this object determines which specific component will be rendered inside: <div [ngSwitch]="poolModel.runtimeType.toString()"> <template ngSwitchCase="CryptonoteMiningPool">& ...

Utilizing BehaviorSubject to dynamically display components based on conditions

I have a basic Service that looks like this: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class HighlightsService { private _highlightedTab: string = ''; highli ...

My previously functioning TypeScript code suddenly ceased to work after I ran the yarn install command

Everything was running smoothly with my TypeScript code, both locally and on the server. However, after restarting the production code, I encountered errors (which required me to reinstall packages with yarn install). Strangely enough, when I try to yarn i ...

Troubleshooting Cross-Origin Resource Sharing (CORS) issues with Font Awesome font in

For a while now, I've been using Angular and Material without any issues. However, recently I encountered a problem that has me puzzled. When running my Angular app from IntelliJ, an error message appeared in the console. The error stated: Access to ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

The upcoming router is not compatible with the NextPage type

I am currently working on introducing dynamic routing into an application that was originally designed with static routes. However, I am facing some confusion as I encounter TypeScript errors that are difficult for me to understand. Below is the code snipp ...

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

Vertical and horizontal tabs not functioning properly in Mat tabs

I successfully created a vertical material tab with the code below, but now I am looking to incorporate a horizontal tab inside the vertical tab. Attempting to do so using the code provided results in both tabs being displayed vertically. Below is my code ...

Customize the color of a specific day in the MUI DatePicker

Has anyone successfully added events to the MUI DatePicker? Or does anyone know how to change the background color of a selected day, maybe even add a birthday event to the selected day? https://i.stack.imgur.com/or5mhm.png https://i.stack.imgur.com/so6Bu ...

"Production mode is experiencing a shortage of PrimeNG(Angular) modules, while they are readily accessible in development

I've been diligently working on an Angular application that heavily relies on PrimeNG as the UI component framework. Initially, I had no issues deploying my app with Angular version 9 and PrimeNG version 8. However, a while ago, I decided to upgrade t ...

Looking for guidance on creating a TypeScript interface within React?

How can I properly declare the tagItems in the following code? I am currently getting a warning in VSCode that reads: (property) tagItems: [{ id: number; label: String; name: String; state: Boolean; }] Type '[{ id: number; label: stri ...

Switching from the HTTPS to HTTP scheme in Angular 2 HTTP Service

I encountered the following issue: While using my Angular service to retrieve data from a PHP script, the browser or Angular itself switches from HTTPS to HTTP. Since my site is loaded over HTTPS with HSTS, the AJAX request gets blocked as mixed content. ...

What is the correct way to declare a class as global in TypeScript?

To prevent duplication of the class interface in the global scope, I aim to find a solution that avoids redundancy. The following code snippet is not functioning as intended: lib.ts export {} declare global { var A: TA } type TA = typeof A class A { ...

Guide to populating a dropdown list using an array in TypeScript

I'm working on a project where I have a dropdown menu in my HTML file and an array of objects in my TypeScript file that I am fetching from an API. What is the best approach for populating the dropdown with the data from the array? ...

Put the item at the start of a viewable list

I have a critical Angular component that efficiently loads data into an Observable<Item[]> using a cleverly implemented BehaviorSubject<Item[]> triggered by the scroll position of a container reaching the bottom. The essential properties and t ...

Dynamic value for href in div using Angular

Implementing a dynamic submenu using Angular is my current project. At the moment, I have set the href attribute with hardcoding as shown below: <ng-template #preSelectionMenuItem let-preSelections="preSelections"> <div class=' ...

How can a child component trigger an event in its parent component?

Currently, I have tabs implemented with a form and a button in tab1. In the parent component, there is an event that deactivates the current tab and activates the next one. Can anyone advise on how to call this event from the child component? gotosecond ...

When a MatFormFieldControl both implements ControlValueAccessor and Validator, it can potentially lead to a cyclic

I am attempting to develop a custom form control by implementing MatFormFieldControl, ControlValueAccessor, and Validator interfaces. However, I encounter issues when including NG_VALUE_ACCESSOR or NG_VALIDATORS. @Component({ selector: 'fe-phone-n ...