Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in NgClass with method call and variable

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,
    };
}
like image 361
Martijn Bakker Avatar asked Jan 09 '17 11:01

Martijn Bakker


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.

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 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.

What is difference between NgStyle and ngClass?

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.


1 Answers

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.

like image 82
Günter Zöchbauer Avatar answered Sep 22 '22 00:09

Günter Zöchbauer