FacundoGFlores FacundoGFlores - 10 months ago 100
TypeScript Question

Model driven forms - Validators issue

I am testing a simple app. These are my files:


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

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');

And this 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 class="form-field">
<input type="text" formControlName="password">
<button type="submit" [disabled]="!form.valid">Submit</button>

But it is not recognizing the
well, because when I write the
it enables the submit button, then if I put the firstname in blank, the input never change to red.

What am I doing wrong?


I created a demo here


Answer Source

The angular validator sets the ng-invalid css class if the validation fails. However you haven't defined ng-invalid in your CSS, so you don't get a red border.

If you define the style in the CSS it works:

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

Don't exactly know why the minLength(5) validator for the password allows an empty password. Either it's an angular bug or intended behavior and you need to combine it with the required validator.