Angular 2 add value to ngClass with interpolation

Suppose I have some objects in an array (the "items" array is called), for example { title: "Title", value: true }, and I use ngFor to display them, for example:

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

Now let's say that I want to map the class to h1 based on if item.value true or false. How can i do this?

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

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

thank

+4
source share
5 answers

You can add a conditional class as follows:

<h1 *ngFor="let item of items" 
     [class.some-class]="item.value === true">
     {{ item.title }}
</h1>

Remember that the syntax *ngForactually extends to template. In your example, it will expand:

<template ngFor let-item [ngForOf]="items">
    <h1 [class.some-class]="item.value === true">
       {{ item.title }}
    </h1>       
</template>

When you see it expanded, you can understand why you can use the directive [class.xyz]with the input variable of the template item.

+4
source

You do not have to interpolate it. Just leave it {{}}. This will interpolate it on the string. Leaving this, you get a boolean value that is great for[class.some-class]

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

Other options

, , . css, true/false

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

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

[ngClass]="getClasses(value)"

.

+1

ngClass h1.

<h1 *ngFor="let item of items" [ngClass]="{'cssClass': item.value }">{{ item.title }}</h1>
0

item.value. . :

[ngClass.class-you-want-add] = "item.value === true"

, . , , :

[ngClass] = "{'class-you-want-add' : isValue("OneValue")}"

:

isValue(val:string) {
   return this.item.value == val;
}
0

ngClass ( dynamicValue @Input() ):

<div [ngClass]="[dynamicValue]"></div>

:

<div [ngClass]="[dynamicValue, secondDynamicValue, thirdDynamicValue]"></div>

. :

<div [ngClass]="[dynamicValue, (isRounded ? 'rounded' : '')]"></div>

This will apply the dynamic value class name and also conditionally apply the rounded class in case isRounded is true.

0
source

Source: https://habr.com/ru/post/1654634/


All Articles