我有一個陣列,我需要使用 *ngFor 在兩個不同的部分顯示其資料。就像我有兩個部分:第 1 部分和第 2 部分。從下面的陣列中,我需要顯示在第一個標簽內具有值 section1 的鍵和在第二個標簽內具有值作為 section2 的鍵。我已經嘗試了很多但無法這樣做,這對于 Angular 來說是相當新的。請幫忙!注意:我不能使用兩個不同的變數,然后在 ts 檔案中將其過濾掉,然后在我的 *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>
uj5u.com熱心網友回復:
將資料過濾到可以迭代的 2 個單獨串列中
const data = [{age:"29",data1:"section1"},{age:"30",data1:"section2"},{age:"22",data1:"section1"},{age:"32",data1:"section2"}];
const section1data = data.filter(x => x.data1 === "section1");
const section2data = data.filter(x => x.data1 === "section2");
<div>
<ng-container *ngFor="let data of section1data">
<p>Section 1</p>
<h1>{{data.age}}</h1>
</ng-container>
<ng-container *ngFor="let data of section2data">
<p>Section 2</p>
<h1>{{data.age}}</h1>
</ng-container>
</div>
uj5u.com熱心網友回復:
最簡單的方法是制作兩個 *ngFor。如果您不能“重復”“內部 html”,則可以使用*ngTemplateOutlet
<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>
如果您只想要一個獨特的回圈,您需要使用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>
在哪里
.wrapper{
display:flex;
flex-direction: column;
}
您可以在此stackbliz中看到這兩種方法
uj5u.com熱心網友回復:
您可以嘗試如下。
組件.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;
}, {});
}
mySortingFunction = (a, b) => {
return a.key > b.key ? -1 : 1;
};
}
組件.html
<div *ngFor="let item of sortedData | keyvalue: mySortingFunction">
<h2>{{ item.key }}</h2>
Key: <b>{{ item.key }}</b> and Value: <b>{{ item.value | json }}</b>
</div>
你也可以排序sortedData。
作業演示
如果您有任何問題,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/419502.html
標籤:
上一篇:如何使單元格自動轉到新行
