0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.