我想遍历一个对象的键值对,并在每行显示两个项目。我查看了其他类似Example的示例,但我不知道如何向其中添加键值。
这是我的代码:
<div *ngFor="let item of book.bookData.privateData | keyvalue; index as i; let even = even">
<div fxFlex="100" fxLayout="row" *ngIf="even">
<div fxFlex="50" fxLayout="column">
Key: <b>{{book.bookData.privateData[i].key}}</b> and Value: <b>{{book.bookData.privateData[i].value}}</b>
</div>
<div fxFlex="50" fxLayout="column">
Key: <b>{{book.bookData.privateData[i+1].key}}</b> and Value: <b>{{book.bookData.privateData[i+1].value}}</b>
</div>
</div>
</div>
这不起作用,因为key
对象上没有value
和privateData
属性,这些属性已分配给item
。
在此先感谢您的帮助!
编辑:
以下是我要实现的目标的可行示例,但这显然不是一种有效的方法:
<div *ngFor="let item of bookState.bookData.privateData | keyvalue; index as i; let even = even">
<div fxFlex="100" fxLayout="row" *ngIf="even">
<div fxFlex="50">
<div *ngFor="let deeperItem1 of bookState.bookData.privateData | keyvalue; index as i2">
<div *ngIf="i2 === i">
<b>INDEX {{i2}} and {{i}} </b>Key: <b>{{deeperItem1.key}}</b> and Value: <b>{{deeperItem1.value}}</b>
</div>
</div>
</div>
<div fxFlex="50">
<div *ngFor="let deeperItem2 of bookState.bookData.privateData | keyvalue; index as i3">
<div *ngIf="(i3-1) === i">
<b>INDEX {{i3}} and {{i}} </b>Key: <b>{{deeperItem2.key}}</b> and Value: <b>{{deeperItem2.value}}</b>
</div>
</div>
</div>
</div>
</div>
EDIT2:
要指定一个问题:问题不是键值管道不起作用,而是问题在于如何有效地向这些值添加索引以显示每行项目的x量(在我的情况下为2)。 抱歉造成任何误会!
答案 0 :(得分:1)
这取决于您要迭代的结构。 Here您可以找到以下示例:
@Component({
selector: 'keyvalue-pipe',
template: `<span>
<p>Object</p>
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
<p>Map</p>
<div *ngFor="let item of map | keyvalue">
{{item.key}}:{{item.value}}
</div>
</span>`
})
export class KeyValuePipeComponent {
object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
map = new Map([[2, 'foo'], [1, 'bar']]);
}
在您的情况下,如果您没有键值结构,请使用映射例,如下所示:
<div *ngFor="let item of book.bookData.privateData | keyvalue; let i=index">
<div fxFlex="100" fxLayout="row" *ngIf="i%2 === 0">
<div fxFlex="50" fxLayout="column">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>
<div fxFlex="50" fxLayout="column" *ngIf="(book.bookData.privateData|keyvalue)[i+1]">
Key: <b>{{(book.bookData.privateData|keyvalue)[i+1].key}}</b> and Value: <b>{{(book.bookData.privateData|keyvalue)[i+1].value}}</b>
</div>
</div>
</div>
答案 1 :(得分:0)