gpt4 book ai didi

angular - 如何使用 *ngFor 仅迭代前几个元素

转载 作者:行者123 更新时间:2023-12-05 08:14:52 26 4
gpt4 key购买 nike

我正在尝试开发一个 Angular (版本 6)应用程序,并且正在使用 *ngFor 来迭代数组。在 HTML 中,由于输出设计变得不均匀,我只想查看前 8 个元素。其余元素基本上可以存储用于下一个按钮调用。我知道一种方法是将我在其上调用 *ngFor 的数组本身限制为 8,但这似乎更像是一种黑客攻击。任何帮助将非常感激。提前致谢。HTML----->

<div *ngIf="!isloading" style = "padding-right: 300px; padding-left: 300px">
<ng-container *ngIf="cards">
<div *ngFor ="let card of cards">
<app-card [card]="card" ></app-card>
</div>
</ng-container>
</div>
<div class ="loader" *ngIf = "isloading">

JS--->

@Component({
selector: 'app-feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {
@Input() cat :string;
@Input() sucat:string;



//These 4 to represent current feed cat and supercat
private curcat : string;
private cursu : string;
private page : number;
//to determine if page loading
private isloading : boolean = false;


//These to deal with the the JSON of the response Data
private cards : Card[] = [];
private itemcount : number;
private lastpage : number = 10;
constructor(private contentservice: ContentService) { }

ngOnChanges(changes : SimpleChange){
this.currentfeedparam(this.cat,this.sucat);
this.fetchdata(this.cursu,this.curcat);
}

ngOnInit(){
}

currentfeedparam(c:string,s:string){
//this fucntion to set feed status
this.curcat = c;
this.cursu = s;
this.page = 1;
}

fetchdata(su :string,cat : string){
this.isloading = true;
if(this.lastpage >= this.page){
this.contentservice.getcontentdata(cat,su,this.page)
.subscribe((response) => {
this.isloading = false;
const data = new JsonData(response);
this.lastpage = data.lastPage;
console.log(this.page+' '+this.lastpage);
this.page++;//
this.cards = data.items;
});

}
else{
console.log('last page reached');
this.isloading = false;
}
}

}

最佳答案

你可以试试这个解决方案

您可以使用 slice 管道。

<div *ngIf="!isloading" style = "padding-right: 300px; padding-left: 300px">
<ng-container *ngIf="cards">
<div *ngFor ="let card of cards | slice:0:8;">
<app-card [card]="card" ></app-card>
</div>
</ng-container>
</div>
<div class ="loader" *ngIf = "isloading">

关于angular - 如何使用 *ngFor 仅迭代前几个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50908491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com