Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Pass a function to the ngClass tag on the template

I have done some searching on this but haven't come across anything that works.

When i pass a function to the ngStyle i get the following error:

Expression 'getClass()' in ProductView has changed after it was checked.

My Template looks like:

<div class="itemContainer">
    <div class="well imageHolder" [ngClass]="getClass()">
        <img [src]="'img/thumbs/' + item.images[0]" class="productImage" id="productImage">
    </div>
</div> 

Im not sure what would fix this or even if it can currently be done. I have noticed that this error also occurs with ngStyle.

All help would be appreciated.

like image 656
Matt McNabb Avatar asked Jan 27 '16 12:01

Matt McNabb


People also ask

Can we call method in ngClass?

You can use a method and a variable to construct the classes-string for the ngClass. In Template then you can use a method and a variable to construct the classes-string for the ngClass.

How do you add conditions to ngClass?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can we use NgStyle and ngClass together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

How do you use ngClass directive?

AngularJS ng-class DirectiveIf it is a string, it should contain one or more, space-separated class names. As an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value. The class will only be added if the value is set to true.


1 Answers

The answer is simple, you can do that with a function, just make sure the function will return the class name

on html:

<div [ngClass]="getClassByValue('a')"> My Div</div>

on ts file:

  getClassByValue(value: string) {
    switch (value) {
      case "a": return "class-a";
      case "b": return "class-b";
    }
  }

will end up with class name "class-a" on your element.

Hope it helps :)

like image 185
Liad Livnat Avatar answered Nov 16 '22 01:11

Liad Livnat