我正在try 重构一小段HTML,以便从*ngFor指令迁移到新的@For指令
<mat-menu #clientsMenu="matMenu">
<ng-container *ngFor="let item of clientMenu | keyvalue">
<button mat-menu-item [matMenuTriggerFor]="sub_menu">{{ item.key }}</button>
<mat-menu #sub_menu="matMenu" class="menu">
<button *ngFor="let p of item.value" mat-menu-item (click)='changePlanta(p)'>
<div>
<span style="padding-right:10px;">{{p.nome_planta}}</span>
<span>{{p.id_planta}}</span>
</div>
</button>
</mat-menu>
</ng-container>
</mat-menu>
ClientMenu不是一个数组,而是一个对象,因此在这个早期版本中,使用KeyValue管道来迭代键(字符串)和值(对象数组).
我试着保持同样的逻辑:
<mat-menu #clientsMenu="matMenu">
@for (client of clientMenu | keyvalue; track client){
<button mat-menu-item [matMenuTriggerFor]="sub_menu">{{ client.key }}</button>
<mat-menu #sub_menu="matMenu" class="menu">
@for (planta of client.value; track planta){
<button mat-menu-item (click)='changePlanta(planta)'>
<div>
<span style="padding-right:10px;">{{planta.nome_planta}}</span>
<span>{{planta.id_planta}}</span>
</div>
</button>
}
</mat-menu>
}
</mat-menu>
但是我在"client.value"中得到了error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that returns an iterator.
,它应该是一个array.
类代码如下:
public clientMenu = {};
async ngOnInit() {
this.routeSubscription = this.routeGuards.authorized.subscribe(async (authorized) => {
if (authorized){
if (this.user.isUgm()){
this.user.plantas = await this.http.centralGet('get_plantas');
new Set(this.user.plantas.map(p=>p.nome_cliente)).forEach(c=>{
this.clientMenu[`${c}`]= this.user.plantas.filter(p=>p.nome_cliente == c).sort((p1, p2) => p1.nome_planta.localeCompare(p2.nome_planta))
})
console.log('this.clientMenu', this.clientMenu)
};
};
});
};
clientMenu
被记录为这样的东西(简化):
{ client1: [{id_planta: 1, nome_planta: 'planta1'}, {id_planta: 2, nome_planta: 'planta2'}], client2: [...same logic...] }
在这种情况下如何使用@for?