I have the following code:
<td *ngFor="let prop of props"
[ngClass] = "{
componentClasses[prop]: true
}"
>
Something
</td>
componentClasses looks like this:
componentClasses = {'id': 'class1', 'name': 'class2', 'salary': 'class3'};
this.props looks like this:
this.props = ['id', 'name', 'salary'];
Why do I want to do this? So that I won't hardcode every class. I would automate it instead, which is useful if you have a big table with different css properties.
The problem is:
This syntax doesn't work. ngClass doesnt seem to like this kind of structure inside object[prop]:
.
I tried the code below as well, but without any success.
'`$(componentClasses[prop])$`': true
Can anybody help me with this?
CodePudding user response:
in html we use props only not this.props
<td *ngFor="let prop of props"
[ngClass] = "{
componentClasses[prop]: true
}"
>
Something
</td>
CodePudding user response:
move it to the ts? Also, use the ngFor
will result in multiple td
<td
[ngClass] = "classNames"
>
Something
</td>
componentClasses = {'id': 'class1', 'name': 'class2', 'salary': 'class3'}
props = ['id', 'name', 'salary']
get classNames(){
return this.props.reduce((acc,key)=>acc[componentClasses[key]]=true,{})
}
or
componentClasses = {'id': 'class1', 'name': 'class2', 'salary': 'class3'}
props = ['id', 'name', 'salary']
get classNames(){
return this.props.map((key)=>componentClasses[key])
}
CodePudding user response:
you have some reduddant code
[ngClass]="componentClasses[prop]"
UPDATE: pass it as an array:
[ngClass]="[componentClasses[prop], componentClasses[prop] '1' ]"