首页 > 解决方案 > Angular Forms,ng-valid 始终存在

问题描述

在角形教程中,使用“ng-valid”来指示组件中的名称文本框何时不为空。

(教程: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>

我们添加一个 forms.css 文件,内容如下:

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

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

以及应用程序的 index.js 文件中的引用:

<!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>

根据教程,当擦除“name”的内容时,ng-valid 应该消失并ng-invalid出现在它的位置。

我所看到的是ng-valid保留并ng-invalid只是添加到类名的末尾。

此行为导致 angular 无法从文件中应用正确的(红色)样式,forms.css因为 ng-valid 仍在类名中。

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

标签: angular

解决方案


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">

推荐阅读