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

Understanding the Union Type in Typescript and Its Application in Angular Development

I came across this piece of code: interface Course { code: string; name: string; user: number | { id: number; name: string; }; } This indicates that a course object can contain either the user object or the user key. When fetching the cour ...

``Error Message: TypeORM - could not establish database connection

I encountered an issue while running my project built with Typescript, Typeorm, and Express. The error message received when running the dev script was: connectionNotFoundError: Connection "default" was not found The content of my ormconfig.json ...

There was an issue retrieving the token in the interceptor. The type 'Promise<void | Observable<HttpEvent<any>>>' does not match the expected type 'Observable<HttpEvent<any>>'

I am currently working on developing an interceptor that sends the token along with requests for the Api. In order to store user information, I am utilizing the @ionic/storage library. However, I am facing an issue where my interceptor cannot access the t ...

The outcome of data binding is the creation of a connected data object

I am attempting to link the rows' data to my view. Here is the backend code I am using: [Route("GetCarCount")] [HttpGet] public async Task<long> Count() { return await _context.Cars.CountAsync(); } ...

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

Leverage the power of a useRef hook to dynamically update a state value within React, even when the object is potentially

I'm running into an issue with the useRef hook, as I'm receiving the error "object is possibly null" when attempting to use it to set a stateful object. const jselectRef = useRef<HTMLButtonElement>(null) const [defaultHeight, setDefaultHeig ...

Methods for closing a modal popup on button click

In my AppComponent, there is a login button that triggers a SigninComponent modal popup when clicked. I am trying to figure out how to close the opened modal popup when a button is clicked. Below is the code snippet: app.component.html <ng-template # ...

Exploring component communication within Angular 8

In Angular8, I have two components - the add-files component and the Discussion Component. Within the Discussion component, there is a button as shown below: <app-add-files></app-add-files> <div class="col-12 col-sm-6 col-lg-6"> ...

identifiers that have been duplicated errors

My journey with VS 2017 and angular 2 started off smoothly, but I hit a roadblock when I encountered 352 errors upon restarting my machine. The errors were mostly "Duplicate Identifier errors," and after some investigation, I realized that I had the file i ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

Issue detected in the console: Angular and Express code linked with status code 200 displaying an error

I am attempting to delete data along with an image connected to that data via an image Id using a get route (since the delete route didn't work out for me). The data is successfully being deleted, but I keep receiving a 200 OK response followed by an ...

Steps for displaying API Response in a material-table

In my project, I have a component named List which displays data using mat-cards. When a specific mat-card is clicked, it navigates to another component called home. In this home component, the data from the selected mat-card is displayed within another ma ...

Datatable - pagination - retrieving data from a specific page

Can someone tell me how to retrieve the records from a specific page in a PrimeNG datatable using Angular 2.0? ...

Obtain the result and retrieve it using `window.angularComponentRef.zone.run`

In my work, I have been able to successfully call angular functions within a component through a static file. For reference, you can visit this link: How to expose angular 2 methods publicly?. The method suggested in the link involves using Zones in Angul ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

Upon initial loading, the default sidenav in Angular is not selected

I need to ensure that the sidenav loads the basic page during the initial load. This is controlled by the routing.ts file shown below: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; i ...

NestJs encountering issues with reading environment variables

I used the instructions from the Nest documentation to set up the configuration, however, it's not functioning correctly. app.module.ts @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TypeOrmModule.forRoot(config), AuthMo ...

Dragging and dropping elements using Angular's CDK into a Material dialog box

I am currently facing a challenge while trying to implement Drag and Drop functionality using Angular cdk. My issue arises when attempting to drag an element into a Dialog, which is nested within the container that holds the cdkDropListGroup. To visually r ...

Using Angular 2 to Showcase JSON Array Data with Component Selector

I am struggling to showcase a specific array value, taxes, using the component selector without any success. At the moment, the component selector is displaying all values in the template/model. My goal is to only display the taxes value of the model. use ...