I want to use [ngClass]
with a method call that returns an object like {currentWeek: true}
and I want to add the var week.state
that can have the value rejected
.
I want that the HTML looks like this: <div class="currentWeek rejected"></div>
but when I use it I get this error:
Error in ./FlexCalendar class FlexCalendar - inline template:29:13 caused by: NgClass can only toggle CSS classes expressed as strings, got [object Object]
How can I combine a method call and a variable into the ngClass? Something like [ngClass]=[setWeekClasses(week), week.state]
setWeekClasses(week: Week): Object {
let state: string = this.state(week.state);
return {
'currentWeek': week.weekNumber === this.selectedDate.getWeekNumber(),
[week.state]: true,
};
}
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.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
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.
The NgClass and NgStyle directives are used to apply style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.
Binding to a method or function is discouraged and returning a new object instance is especially bad.
You should at least cache the result
oldWeek;
oldStyles;
setWeekClasses(week: Week): Object {
if(this.oldWeek != week) {
let state: string = this.state(week.state);
this.oldStyles = {
'currentWeek': week.weekNumber === this.selectedDate.getWeekNumber(),
[week.state]: true,
};
this.oldWeek = week;
}
return this.oldStyles;
}
then you can use it like
[ngClass]="setWeekClasses(week)"
This binding
[ngClass]=[week.state, getWeekState(week)]
is invalid because ngClass
supports a string, a list of strings and an object with string values while [week.state, getWeekState(week)]
results in a list that contains a string and an object, which is not supported.
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