I have a single array whose data I need to display at two different sections using *ngFor. Like I have two sections: Section 1 and Section 2. From the below array I need to display keys having values section1 inside the first tag and those having values as section2 inside the second tag. I have tried a lot but not able to do so, considerably new with Angular. Please help! Note: I cannot use two different variables and then filter it out in ts file and then use those 2 variables inside my *ngFor.
arr=[{age:"29",data1:"section1"},{age:"30",data1:"section2"},{age:"22",data1:"section1"},{age:"32",data1:"section2"}]
HTML Code:
<div *ngFor="let data of arr;">
<p>Section 1</p>
<h1>{{data.age}}</h1>
<p>Section 2</p>
<h1>{{data.age}}</h1>
</div>
The easy way if make two *ngFor. You can use *ngTemplateOutlet if you can not "repeat" the "inner html"
<div>Section 1</div>
<div *ngFor="let item of arr">
<ng-container *ngIf="item.data1 == 'section1'">
<ng-container
*ngTemplateOutlet="template; context: { $implicit: item }"
></ng-container>
</ng-container>
</div>
<div>Section 2</div>
<div *ngFor="let item of arr">
<ng-container *ngIf="item.data1 == 'section2'">
<ng-container
*ngTemplateOutlet="template; context: { $implicit: item }"
></ng-container>
</ng-container>
</div>
<ng-template #template let-item>
{{ item | json }}
</ng-template>
If you only want an unique loop you need "play" with css flex order
<div class="wrapper">
<div [style.order]="0">Section 1</div>
<div [style.order]="1000">Section 2</div>
<div
*ngFor="let item of arr; let i = index"
[style.order]="item.data1 == 'section2' ? 1000 + i : 1 + i"
>
{{ item | json }}
</div>
</div>
where
.wrapper{
display:flex;
flex-direction: column;
}
You can see the two approach in this stackbliz
You can try like below.
component.ts
import { Component, OnInit, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
name = 'Angular ' + VERSION.major;
arr = [
{ age: '29', data1: 'section1' },
{ age: '30', data1: 'section2' },
{ age: '22', data1: 'section1' },
{ age: '32', data1: 'section2' },
];
sortedData;
constructor() {}
ngOnInit() {
this.sortedData = this.arr.reduce((acc, curr) => {
if (acc.hasOwnProperty(curr.data1)) {
acc[curr.data1].push(curr);
return acc;
}
acc[curr.data1] = [curr];
return acc;
}, {});
}
}
component.html
<div *ngFor="let item of sortedData | keyValue">
<h2>{{ item.key }}</h2>
<div *ngFor="let obj of item.value">{{ obj.age }}</div>
</div>
key-value pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'keyValue',
})
export class KeyValuePipe implements PipeTransform {
transform(input: any): any {
let keys = [];
for (let key in input) {
if (input.hasOwnProperty(key)) {
keys.push({ key: key, value: input[key] });
}
}
return keys;
}
}
Updated code.
Let me know if you have any issue.