我有一个由公寓编号排序的公寓对象的Observable数组(从Firebase查询返回):
[
{number: 10, color: white, ...},
{number: 11, color: blue, ....},
{number: 20, color: red, ...}
{number: 32, color: red, ...}
]
每间公寓都有一个电话号码。
公寓号码的第一位数字决定了他的姓氏。
示例:
Apartment number: 32 = 3th floor
Apartment number: 53 = 5th floor
每次更改楼层时,我需要显示带有楼层号的标头。像这样:
1th Floor:
- 10
- 11
- 12
...
2th Floor:
- 20
- 21
...
3th Floor:
- 30
- 31
....
我该如何使用ngFor和异步管道?
为了简单地显示我正在使用的以下代码,列出所有公寓的列表:
<div *ngFor="let apartment of apartment$ | async">
<h2>{{apartment.number}}</h2>
</div>
答案 0 :(得分:1)
此处正在运行示例Working Example
ts代码:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
floor: any[] = [];
apartments: Array<any> = [
{ number: 10, color: "white" },
{ number: 11, color: "blue" },
{ number: 20, color: "red" },
{ number: 32, color: "red" },
{ number: 33, color: "red" },
{ number: 34, color: "red" }
];
constructor() {
for (let i = 0; i < this.apartments.length; i++) {
this.calculateFloor(this.apartments[i]);
}
}
calculateFloor(apartment){
if (Math.floor(apartment.number / 10) > 0) {
if (this.floor.indexOf(Math.floor(apartment.number / 10)) == -1) {
this.floor.push(Math.floor(apartment.number / 10));
}
return { num: apartment.number, status: true, floor: Math.floor(apartment.number / 10) };
}
}
calculateApartment(apartment, floor){
if (Math.floor(apartment.number / 10) == floor) {
return true
} else {
return false
}
}
}
HTML:
<div *ngFor="let f of floor;">
<h1>{{f}} th Floor</h1>
<li>
<ul *ngFor="let apartment of apartments">
{{calculateApartment(apartment, f)? apartment.number: ''}}
</ul>
</li>
</div>
答案 1 :(得分:1)
如果要计算楼层数,可以
//Add to each this.apartments element a property:floor
this.apartments=this.apartments.map(ap=>
{
return {...ap,floor:Math.floor(ap.number/10)}
})
//Create an array with unique values of "floor"
//And add the property "apartments"
const floor=this.apartments.filter((item, pos)=> {
return this.apartments.findIndex(i=>item.floor==i.floor) == pos;
}).map(f=>{
return{
floor:f.floor,
apartments:this.apartments.filter(a=>a.floor==f.floor)
}
}
答案 2 :(得分:0)
如果您只想使用某些模板逻辑(并使用async
)来执行此操作,则可以利用* ngFor的index属性:
<div *ngFor="let apartment of apartments | async; let i = index">
<h1 *ngIf="i === 0 || (apartment.number / 10 >> 0) !== (apartments[i-1].number / 10 >> 0)">{{(apartment.number / 10 >> 0)}}th Floor {{apartment.number}}</h1>
<h2>{{apartment.number}}</h2>
</div>
其中(apartment.number / 10 >> 0)
应将number
除以10且无余数...