Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 add value to ngClass with interpolation

Lets say I have some objects in an array (lets call the array "items") like { title: "Title", value: true } and I use ngFor to display them like:

<h1 *ngFor="let item of items">{{ item.title }}</h1>

Now lets say I want to display a class on the h1 based on if item.value is true or false. How can I do that?

I can't add [class.some-class]="{{ item.value }}". Basically, how can I get the true or false value for the current item into something like ngClass? Am I missing an obvious way to do this in Angular 2?

(Btw, I know I can do it by adding class="{{ item.value | pipe }}" to the h1 and piping the value and returning the correct class based on the values true and false, but it seems like there should be a better way.)

Thanks

like image 395
user5021816 Avatar asked Sep 15 '16 00:09

user5021816


1 Answers

You shouldn't interpolate it. Just leave out the {{}}. This will interpolate it to a string. Leaving those out will give you the boolean value, which is perfectly valid for [class.some-class]

[class.some-class]="item.value"

Other options

You can also use object notation either inline or taken from the component, if you have a few different classes. Basically the property is the css class, and the value is the true/false

[ngClass]="{'some-class': item.value }"

Or get the object from the component

getClasses(value) {
  return { 'some-class': value }
}

[ngClass]="getClasses(value)"

See Also

  • Template Syntax: NgClass
like image 111
Paul Samsotha Avatar answered Sep 20 '22 14:09

Paul Samsotha