user3057416
user3057416

Reputation: 105

How to use a function to evaluate ngClass conditional statement in Angular 2

So within my *ngfFor loop I have this

[ngClass]="{'first':isStartDate(event,day)}"

where isStartDate is a function in my component.

error thrown is

"Unexpected token : "

Is it possible to to use a function here?

Upvotes: 1

Views: 5487

Answers (5)

Roman C
Roman C

Reputation: 1

You can use expression in ngClass:

[ngClass]="'{first:'+ifStartDate(event,day)+'}'"

Upvotes: 0

Amit Chigadani
Amit Chigadani

Reputation: 29705

Yes you can definitely use function in ngClass

[ngClass]="{first: isStartDate(event,day)}"

Upvotes: 0

Suneet Bansal
Suneet Bansal

Reputation: 2702

Best way to implement it:

<div [ngClass]="ifStartDate(event,day)">
</div>

ifStartDate(event, day) {
    let cssClasses;

    if(some condition) {  
      cssClasses = {
       'first': true
      } 
    } else {  
      cssClasses = {
       'second': true,
       'third': true 
      } 
    }

    return cssClasses;
}

In this way you can also apply multiple classes over div based on some condition.

Upvotes: 1

You can also give dynamic class as below:

[ngClass]="ifStartDate(event,day) ? 'first' : ''"

Upvotes: 1

Bharat Chauhan
Bharat Chauhan

Reputation: 3322

ifStartDate function is return only boolean value

[class.first]="ifStartDate(event,day)"

Upvotes: 4

Related Questions