AdelaM
AdelaM

Reputation: 78

Add red border to multiple input fields with errors

I am currently working on an angular application. I have a form and I used *ngFor to add input fields because the number of inputs and their type is not always the same (it depends on the data received from backend). When the submit button is pressed, I want to make some validations. How should I add a red border only on those input fields that have errors?

The code looks like this:

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

Upvotes: 0

Views: 1605

Answers (1)

Joziok
Joziok

Reputation: 15

You can create a class redBorder,

.redBorder{
  border-style: solid;
  border-color: green;
}

then you have to initialize an array wich indicates if each element is validated

let validations= []
for (let i = 0; i < this.data.length; i++) {
    validations.push(true);
}

and you have to change this array in the for that you have to create for the validation. In the HTML you have to add the following change, adding [ngStyle]:

<ng-container [ngSwitch]="content.Type"  [ngStyle]="{'redBorder': !correctValidated[i]}"

It will apply the class only when validations[i] is false

Upvotes: 1

Related Questions