Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

Angular 2: Add a class dynamically in ngFor

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?

Upvotes: 2

Views: 848

Answers (1)

Stefan Svrkota
Stefan Svrkota

Reputation: 50623

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

Upvotes: 1

Related Questions