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.
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.
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.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With