Reputation: 693
I have an array with multiple objects, which I want to use in a *ngFor
loop.
I want to loop this with a div
container and want to add a css class to the div container to show the containers next to each other. The css class is defined in the object and I need to convert it to a valid class, like col-sm-6
.
So I created a function to search in the objects for a css class and convert this to a valid css class. But my function only returns 1 css class, and not the correct css class for each object.
Let's look at my code:
Array:
elements = [
{
title: 'Test1',
class: ["ColumnWidth3"]
},
{
title: 'Test2',
class: ["ColumnWidth9"]
}
]
HTML:
<div *ngFor="let column of elements" [ngClass]="columnClass()">
<h1>{{column.title}}</h1>
</div>
Function:
columnClass() {
const columnClass = this.elements.filter((child: any) => child.class.includes('ColumnWidth') >= 0);
columnClass.forEach(element => {
this.item = element.class.find((class:any) => class.indexOf('ColumnWidth') >= 0).split('ColumnWidth').pop();
});
return 'col-sm-' + this.item;
}
}
So what I want to get is the classes col-sm-3
for the first object and col-sm-9
for the second object. And add the css class of each object to the div container of that object.
But my function returns only col-sm-9
.
How can I make sure that both objects get the correct class?
Upvotes: 0
Views: 1978
Reputation: 6424
How about the following example?
Component:
defineClass(classList: string[]) {
const item = classList.find(x => x.startsWith("ColumnWidth"));
return 'col-sm-' + item?.charAt(item.length - 1);
}
Template:
<div *ngFor="let column of elements" [ngClass]="defineClass(column.class)">
<h1>{{column.title}}</h1>
</div>
Upvotes: 2