Software Development Tricky

Tuesday, 18 April 2017

How to add dynamic class in angular 2

Achieve in Following Way

Assume "operation" as string & "todayDate" as current date ((ie) actual scenario today date get from database).

Code look this

HTML:

1
<span [ngClass]="(getTodayClass()=== 'today') ? 'today' : 'not-today'">{{operation}}</span>

CSS:

1
2
3
4
5
6
7
8
<style>
.today {
    background-color:red;
}
.not-today {
    background-color:green;

}

Component:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
//declaraion
todayDate: Date;
operation: string;

private sameDays(d1: Date, d2: Date) {
    return d1.getUTCFullYear() == d2.getUTCFullYear() &&
        d1.getUTCMonth() == d2.getUTCMonth() &&
        d1.getUTCDate() == d2.getUTCDate(); //using UTC methods ensures that two equivalent days in different timezones matching
}

getTodayClass() {
    //variable assign
    this.todayDate = new Date; //this date get from database
    this.operation = "Monday";

    //check condition for database time and current time with help of UTC
    if (this.sameDays(this.todayDate, new Date)) {
        return 'today';
    } else {
        return 'not-today';
    }
}

Followers