2

I am trying to add a class dynamically inside *ngFor. When I enter invalid text in textbox, it will change the textbox border to red color.

HTML

<div *ngFor="let appt of appointments">
    <div class="ctrl-wpr" *ngIf="appt.personVitals && appt.personVitals.weight">
        <md-input class="ctrl-wpr__ctrl" [(ngModel)]="appt.personVitals.weight.weight" [ngClass]="{'error_bgcolor': errcolor }" (keyup)="validate(appt.personVitals.weight.weight)"
            (blur)="updatePersonvitals(appt.personVitals.weight, 'kgs', appt.patientInfo.id)">
        </md-input>
    </div>
</div>

script

validate(wt: any) {
        if (/^\d+(\.\d{1,3})?$/.test(wt)) {
            this.errcolor = false;
        }
        else {
            this.errcolor = true;
        }
    }

CSS

.error_bgcolor {
        .md-input-underline .md-input-ripple  {  
            background-color: red;
            opacity: 1;
            -webkit-transform: scaleY(1);
            transform: scaleY(1);
        }        
    }

The problem I have is when invalid text is entered, red color is applying to all textboxes, not just the one that is invalid. How can I make it more dynamic?

1 Answer 1

1

Problem is that you are using one same value (value of variable errcolor) in all ngClass directives, so if one of the inputs is invalid, all of them are marked as invalid. You can do something like this:

<div *ngFor="let appt of appointments">
    <div class="ctrl-wpr" *ngIf="appt.personVitals && appt.personVitals.weight">
        <md-input class="ctrl-wpr__ctrl" [(ngModel)]="appt.personVitals.weight.weight" [ngClass]="{'error_bgcolor': validate(appt.personVitals.weight.weight)}" (keyup)="validate(appt.personVitals.weight.weight)"
        (blur)="updatePersonvitals(appt.personVitals.weight, 'kgs', appt.patientInfo.id)">
        </md-input>
    </div>
</div>

And your validate method:

validate(wt: any) {
    if (/^\d+(\.\d{1,3})?$/.test(wt)) {
        return false;
    }
    else {
        return true;
    }
}
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.