Angular Forms, ng-valid is always present

Viewed 260

In the angular form tutorial there is a use of "ng-valid" to indicate when the name text box in the component is not empty.

(Tutorial: https://angular.io/guide/forms)

<div class="form-group">
  <label for="name">Name</label>
  <input type="text" class="form-control ng-untouched ng-pristine ng-valid" id="name"
         required
         [(ngModel)]="model.name" name="name">

</div>

We add a forms.css file with the following content:

.ng-valid[required], .ng-valid.required  {
  border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form)  {
  border-left: 5px solid #a94442; /* red */
}

And a reference in the index.js file of the app:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularHeroForm</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="assets/forms.css">
</head>
<body>
  <app-root></app-root>
</body>
</html>

According to the tutorial, when erasing the content of "name" the ng-valid should disappear and ng-invalid should appear in its place.

What I am seeing is that ng-valid stays and ng-invalid just added to the end of the class name.

This behavior causes angular to not apply the correct (red color) style from the forms.css file because ng-valid is still in the class name.

What did I do wrong and why ng-valid is not disappearing after erasing the name ?

1 Answers

The ng-valid/ng-invalid are classes that Angular adds automatically, and there is no need to add them manually.

If you remove the classes that you added to the input, then your sample will work without any problem.

 <input type="text" id="name" required [(ngModel)]="model.name" name="name">
Related