![](/img/trans.png)
[英]How to render elements if space is available for that element using ngFor in Angular2
[英]How to show 1 element in an array using ngFor Angular2
在我的網站上,如果數組中包含多個元素。 我的模板如下所示。
我希望有一個按鈕可以轉到該數組的下一個元素,並且僅顯示一組數據,並使用該按鈕來控制用戶看到的數組元素。
我當前的代碼如下所示:
<div class='panel-body' *ngIf ='case'>
<h3> Details </h3>
<div id="left-side" *ngFor="let tag of case?.incidents ">
<p>Date: <span class="name">{{tag.date}}</span> </p>
<p>DCU: <span class="name">{{tag.dcu}}</span></p>
<p>Location:<span class="name"> {{tag.location}}</span> </p>
</div>
我當時在考慮使用某種索引或ng容器,或者使用ngIf或ngFor進行一些解決。 我不確定如何執行此操作。
所有幫助將不勝感激!
在這種情況下,您不需要ngFor或ngIf。 您需要一個變量來跟蹤用戶的索引,然后是一個更改該索引的函數。
<h3> Details </h3>
<div id="left-side" >
<p>Date: <span class="name">{{case?.incidents[userIndex].date}}</span> </p>
<p>DCU: <span class="name">{{case?.incidents[userIndex].dcu}}</span></p>
<p>Location:<span class="name"> {{case?.incidents[userIndex].location}}</span> </p>
</div>
<button (click)="changeIndex(-1);">Previous</button>
<button (click)="changeIndex(1);">Next</button>
在component.ts中,您將擁有:
userIndex = 0;
changeIndex(number) {
if (this.userIndex > 0 && number < 0 || //index must be greater than 0 at all times
this.userIndex < this.case?.incidents.length && number > 0 ) { //index must be less than length of array
this.userIndex += number;
}
這也是其他項目的視圖內尋呼系統的標准。
為此,您可以像以下示例一樣使用angular的默認SlicePipe ,
@Component({
selector: 'slice-list-pipe',
template: `<ul>
<li *ngFor="let i of collection | slice:1:3">{{i}}</li>
</ul>`
})
export class SlicePipeListComponent {
collection: string[] = ['a', 'b', 'c', 'd'];
}
您可以在這里找到更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.