html - 为多个有错误的输入字段添加红色边框
问题描述
我目前正在开发一个角度应用程序。我有一个表单,我使用 *ngFor 添加输入字段,因为输入的数量及其类型并不总是相同的(这取决于从后端接收的数据)。当按下提交按钮时,我想做一些验证。我应该如何仅在那些有错误的输入字段上添加红色边框?
代码如下所示:
<div *ngFor="let content of contents; let i = index"
<h6 *ngIf="content.Label">{{ content.Label | translate }}</h6>
<ng-container [ngSwitch]="content.Type"
<input *ngSwitchCase="INPUT_TYPE.TextBox"
#input
value={{content?.Value}}
type="text">
<textarea *ngSwitchCase="INPUT_TYPE.TextBoxMultiLine"
#input
value="{{content?.Value}}">
</textarea>
</ng-container>
</div>
<button type="button"(click)="accept()">Submit</button>
@ViewChildren('input') data;
accept() {
this.data = this.data.toArray();
for (let i = 0; i < this.data.length; i++) {
//validations
if (this.data[i].nativeElement.value....) {
//add red border to the input fields with errors
}
}
解决方案
您可以创建一个类 redBorder,
.redBorder{
border-style: solid;
border-color: green;
}
那么你必须初始化一个数组来指示每个元素是否被验证
let validations= []
for (let i = 0; i < this.data.length; i++) {
validations.push(true);
}
并且您必须在您必须为验证创建的 for 中更改此数组。在 HTML 中,您必须添加以下更改,添加 [ngStyle]:
<ng-container [ngSwitch]="content.Type" [ngStyle]="{'redBorder': !correctValidated[i]}"
仅当validations[i] 为false 时才会应用该类
推荐阅读
- sql - 从新旧表参考更新表列
- python - 带有三引号的 Jupyter Notebook Python 自动文档字符串生成
- xml - 什么是
和 ? 有没有人知道这个? - scala - 如何仅将空数据帧标题写入 csv 文件?
- postgresql - 触发器创建时出现“SET 处或附近的语法错误”
- python - 数据框列值组合?
- compilation - 如果在 symtab 中提到符号但在 readelf 输出的 dynsym 中没有提到符号,这意味着什么?
- typescript - 如何在没有全局 Promise Polyfill 的 Typescript 中使用 async/await
- node.js - 如何制作一个包含猫鼬所需不同字段的数组?
- javascript - 如何获取输入文件数组的所有值