简体   繁体   中英

How to use a return in a forEach loop in Angular?

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM