1

I need to use both function and condition in ngClass like below:

<div [ngClass] = "i==1 ? 'active':'inactive',getclass()">
</div

TS

getclass(){
return 'myclassname'
}

3 Answers 3

1

You can use function as well. You just need to pass as an array like below,

<div [ngClass]="[i === 1 ? 'active': 'inactive', getClass()]"> </div

You can find other ways in this link https://angular.io/api/common/NgClass#description

Sign up to request clarification or add additional context in comments.

Comments

0

Not sure what's the use case of your function here but you can pass i value to the function and call the function only something like

<div [ngClass] = "getclass(i)">
</div

getclass(input){
   let cls=input==1 ? 'active':'inactive';
   return `${cls} myclassname`
}

Comments

0

ngClass accepts objects

<div [ngClass]="{
  active: i === 1,
  inactive: i !== 1,
  myclassname: true
}">
</div>

Otherwise, use an input on the class

<div [ngClass]="getClasses(i)"></div>
getClasses(i: number) {
  const classes: any = { myclassname: true };
  if (i === 1) classes.active = true;
  else classes.inactive = true;
}

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.