Angular 2 ngClass function

chewi picture chewi · May 8, 2018 · Viewed 8.3k times · Source

Hi I was in the midst of creating a wizard/step component. How can I use the ngClass to return css classes based on ->?

I have 5 steps, let's say the user is in the 3rd step. All the previous steps should return a css class named active and the current step (step 3) returns css class active and all the steps after step 3 should return inactive css class.

<div class="step actived">
                    <span [ngClass]="displayActiveness()">Step 1
                    </span>
                </div>
                <div class="divider"></div>
                <div class="step" [ngClass]="displayActiveness()">
                    <span>Step 2
                    </span>
                </div>
.....

TS:

displayActiveness(status) {
        if (this.statusSelected === 'step3') {
            return 'active';
        } else if (
        this.statusSelected === 'step4' || this.statusSelected === 'step5'){
            return 'inactive';
        }
        else if (
            this.statusSelected === 'step1' || this.statusSelected === 'step2'){
                return 'actived';
            }
    }

I am stuck. Can someone please help me on this. Thanks in advance.

Answer

Fetrarij picture Fetrarij · May 8, 2018

Why not set your statusSelected to number and it would be easy to manage?

TS:

statusSelected: number = 1; //step 1 by default
....
displayActiveness(status) {
    if (this.statusSelected === status) {
      return 'active';
    }
    if (this.statusSelected > status) {
      return 'actived';
    }
    if (this.statusSelected < status) {
      return 'inactive';
    }
}

HTMl:

<div class="step"  [ngClass]="displayActiveness(1)">
    <span>Step 1</span>
</div>
<div class="divider"></div>
<div class="step" [ngClass]="displayActiveness(2)">
    <span>Step 2</span>
</div>

with this, next step could be only:

nextStep() {
    this.statusSelected++;
}