首页 > 解决方案 > 为多个有错误的输入字段添加红色边框

问题描述

我目前正在开发一个角度应用程序。我有一个表单,我使用 *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
        }
    }

标签: htmlcssangular

解决方案


您可以创建一个类 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 时才会应用该类


推荐阅读