在 angular2 中访问嵌套数组对象时出现问题
2019-11-25
157
我如何访问下面给出的数组结构。如果我尝试这个
*ngFor="let item of bookingItems[0]"
,我认为它只允许我访问
array[0]
数据。那么
array[1]、array[2]....array[n]
呢?我如何获得它们?
[Array(2)]
0: Array(2)
0: {id: 2, name: "Calark", price: 375, …}
1: {id: 5, name: "Eternis", price: 450, …}
length: 2
__proto__: Array(0)
length: 1
__proto__: Array(0)
组件内部
export class BookingComponent implements OnInit {
bookedItems = [];
constructor(private bookingService:BookingService) { }
ngOnInit(){
this.bookedData();
console.log(this.bookedItems);
}
bookedData(){
this.bookedItems = this.bookingService.getBookedItem();
}
}
模板内部
<h3>Your Bookings:</h3>
<div *ngIf="bookedItems.length > 0; else plainText">
<div class="cart-item" *ngFor="let item of bookedItems[0]">
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img [src]="item.imagePath" alt="{{item.name}}" class="img-responsive" style="max-height: 305px" width="293px">
</div>
<div class="flip-card-back">
<small>
<p>Name: {{item.name}}</p>
<p>Size: {{item.size}}</p>
<p>Price: {{item.price}}</p>
<p>City: {{item.city}}</p>
<p>Address: {{item.address}}</p>
</small>
</div>
</div>
</div><hr/>
</div>
</div>
<ng-template #plainText>
<p>You haven't booked any item. please book to get your booking details!!!</p>
</ng-template>
2个回答
我认为您肯定需要在这里使用双循环,除非您有一个嵌套数组是一个错误。如果不是,您可能应该使用“ng-container”指令,如下所示 =>
<h3>Your Bookings:</h3>
<div *ngIf="bookedItems.length > 0; else plainText">
<ng-container *ngFor="let bookedItem of bookedItems">
<div class="cart-item" *ngFor="let item of bookedItem">
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img [src]="item.imagePath" alt="{{item.name}}" class="img-responsive" style="max-height: 305px"
width="293px">
</div>
<div class="flip-card-back">
<small>
<p>Name: {{item.name}}</p>
<p>Size: {{item.size}}</p>
<p>Price: {{item.price}}</p>
<p>City: {{item.city}}</p>
<p>Address: {{item.address}}</p>
</small>
</div>
</div>
</div>
<hr/>
</div>
</ng-container>
</div>
<ng-template #plainText>
<p>You haven't booked any item. please book to get your booking details!!!</p>
</ng-template>
我希望这对您有所帮助。
millenion
2019-11-25
抱歉,我没有意识到数组是嵌套的。您可以尝试双循环:
<div class="cart-item" *ngFor="let item of bookedItems">
<div class="flip-card" *ngFor="let innerItem of item">
<div class="flip-card-inner">
<div class="flip-card-front">
<img [src]="innerItem.imagePath" alt="{{innerItem.name}}" class="img-responsive" style="max-height: 305px" width="293px">
</div>
<div class="flip-card-back">
<small>
<p>Name: {{innerItem.name}}</p>
<p>Size: {{innerItem.size}}</p>
<p>Price: {{innerItem.price}}</p>
<p>City: {{innerItem.city}}</p>
<p>Address: {{innerItem.address}}</p>
</small>
</div>
</div>
</div><hr/>
</div>
如果我遇到此问题,我会先展平数组,因为只有一层嵌套。
acincognito
2019-11-25