반응형
Angular의 일부 항목으로 반복을 제한하려면 어떻게 해야 합니까?
내 코드:
<li *ngFor="let item of list; let i=index" class="dropdown-item" (click)="onClick(item)">
<template [ngIf]="i<11">{{item.text}}</template>
</li>
저는 어느 지점에서든 10개의 목록 요소만 표시하려고 합니다.여기 답변에서 제안한 것처럼 ngIf를 사용했지만 이로 인해 페이지에 빈 목록 항목(10개 이상)이 표시됩니다.
이것은 제가 보기에 더 단순해 보입니다.
<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>
접근 방식에 더 가까이 다가가기
<ng-container *ngFor="let item of list; i as index">
<li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>
대안
<ng-template ngFor let-item [ngForOf]="list" let-i="index">
<li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-template>
직접 신청할 수 있습니다.slice()
변수에.스택 블리츠 데모
<li *ngFor="let item of list.slice(0, 10);">
{{item.text}}
</li>
예를 들어 배열의 처음 10개 항목만 표시하려고 하면 다음과 같이 SlicePipe를 사용하여 이 작업을 수행할 수 있습니다.
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
이것은 매우 잘 작동합니다.
<template *ngFor="let item of items; let i=index" >
<ion-slide *ngIf="i<5" >
<img [src]="item.ItemPic">
</ion-slide>
</template>
동적으로 제한할 수 있습니다.*ngFor
3진 연산자를 적용하여.
예 1 -
<div *ngFor="let item of (showAllFlag ? list : list.slice(0,2))" >
</div>
@Gunter의 답변 외에도 trackBy를 사용하여 성능을 향상시킬 수 있습니다. trackBy는 인덱스와 항목이라는 두 개의 인수가 있는 함수를 사용합니다.함수에서 개체의 고유한 값을 반환할 수 있습니다.ngFor에 이미 표시된 항목의 렌더링을 중지합니다.html에 아래와 같이 trackBy를 추가합니다.
<li *ngFor="let item of list; trackBy: trackByFn;let i=index" class="dropdown-item" (click)="onClick(item)">
<template [ngIf]="i<11">{{item.text}}</template>
</li>
그리고 당신의 .ts 파일에 이와 같은 기능을 쓰시오.
trackByfn(index, item) {
return item.uniqueValue;
}
html
<table class="table border">
<thead>
<tr>
<ng-container *ngFor="let column of columns; let i = index">
<th>{{ column }}</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of groups;let i = index">
<td>{{row.name}}</td>
<td>{{row.items}}</td>
<td >
<span class="status" *ngFor="let item of row.Status | slice:0:2;let j = index">
{{item.name}}
</span><span *ngIf = "i < 2" class="dots" (mouseenter) ="onHover(i)" (mouseleave) ="onHover(-1)">.....</span> <span [hidden] ="test" *ngIf = "i == hoverIndex" class="hover-details"><span *ngFor="let item of row.Status;let j = index">
{{item.name}}
</span></span>
</td>
</tr>
</tbody>
</table>
<p *ngFor="let group of usersg"><input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}</p>
<p><select [(ngModel)]="usersr_selected.id">
<option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option>
</select></p>
활자 원고
import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
dataGroup: FormGroup;
selectedGroups: string[];
submitted = false;
usersg_checked:any;
usersr_selected:any;
dotsh:any;
hoverIndex:number = -1;
groups:any;
test:any;
constructor(private formBuilder: FormBuilder) {
}
onHover(i:number){
this.hoverIndex = i;
}
columns = ["name", "Items","status"];
public usersr = [{
"id": 1,
"name": "test1"
}, {
"id": 2,
"name": "test2",
}];
ngOnInit() {
this.test = false;
this.groups=[{
"id": 1,
"name": "pencils",
"items": "red pencil",
"Status": [{
"id": 1,
"name": "green"
}, {
"id": 2,
"name": "red"
}, {
"id": 3,
"name": "yellow"
}],
"loc": [{
"id": 1,
"name": "loc 1"
}, {
"id": 2,
"name": "loc 2"
}, {
"id": 3,
"name": "loc 3"
}]
},
{
"id": 2,
"name": "rubbers",
"items": "big rubber",
"Status": [{
"id": 1,
"name": "green"
}, {
"id": 2,
"name": "red"
}],
"loc": [{
"id": 1,
"name": "loc 2"
}, {
"id": 2,
"name": "loc 3"
}]
},
{
"id": 3,
"name": "rubbers1",
"items": "big rubber1",
"Status": [{
"id": 1,
"name": "green"
}],
"loc": [{
"id": 1,
"name": "loc 2"
}, {
"id": 2,
"name": "loc 3"
}]
}
];
this.dotsh = false;
console.log(this.groups.length);
this.usersg_checked = [{
"id": 1,
"name": "test1"
}, {
"id": 2,
"name": "test2",
}];
this.usersr_selected = {"id":1,"name":"test2"};;
this.selectedGroups = [];
this.dataGroup = this.formBuilder.group({
email: ['', Validators.required]
});
}
isChecked(id) {
console.log(this.usersg_checked);
return this.usersg_checked.some(item => item.id === id);
}
get f() { return this.dataGroup.controls; }
onCheckChange(event) {
if (event.target.checked) {
this.selectedGroups.push(event.target.value);
} else {
const index = this.selectedGroups.findIndex(item => item === event.target.value);
if (index !== -1) {
this.selectedGroups.splice(index, 1);
}
}
}
getFormData(value){
this.submitted = true;
// stop here if form is invalid
if (this.dataGroup.invalid) {
return;
}
value['groups'] = this.selectedGroups;
console.log(value);
}
}
CSS
.status{
border: 1px solid;
border-radius: 4px;
padding: 0px 10px;
margin-right: 10px;
}
.hover-details{
position: absolute;
border: 1px solid;
padding: 10px;
width: 164px;
text-align: left;
border-radius: 4px;
}
.dots{
position:relative;
}
<div *ngFor="let item of list;trackBy: trackByFunc" >
{{item.value}}
</div>
ts 파일에서
trackByFunc(index, item){
return item ? item.id : undefined;
}
나는 아래가 좋은 접근법이라는 것을 발견했습니다.
<ul class="list-group col-auto" *ngFor="let result of searchResults.slice(0,10)">
<li class="list-group-item">
<b>{{result.name}}</b>
<p>{{result.email}}</p>
<p>{{result.body | slice:0:64}}</p>
</li>
</ul>
언급URL : https://stackoverflow.com/questions/37818677/how-can-i-limit-ngfor-repeat-to-some-number-of-items-in-angular
반응형
'it-source' 카테고리의 다른 글
Func와 딜러의 차이점은 무엇입니까? (0) | 2023.05.11 |
---|---|
ASP.NET 2.0 - app_offline.htm 사용방법 (0) | 2023.05.11 |
Heroku "psql: FATAL: 나머지 연결 슬롯은 복제되지 않은 슈퍼 사용자 연결을 위해 예약되었습니다." (0) | 2023.05.06 |
INOTIFY 구현변경된 속성 - 더 나은 방법이 있습니까? (0) | 2023.05.06 |
목록에 다른 목록이 있는지 확인합니다. (0) | 2023.05.06 |