You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4实现重复加载同批10条API数据的加载更多按钮

Solution for Repeating "Load More" Data in Angular

Got it, let's get this working exactly how you need it—loading 10 items initially, then appending the same 10 every time the "load more" button is clicked. Here's the complete implementation:

Step 1: Update the Component Class (app.component.ts)

We'll need to store the original 10 items we fetch from the API so we can reuse them for every "load more" click. Here's the full code:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class AppComponent implements OnInit {
  content: any[] = [];
  private originalData: any[] = []; // Store the initial 10 items here

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Fetch initial data from API when the component loads
    this.fetchInitialData();
  }

  fetchInitialData(): void {
    // Replace 'your-api-endpoint-here' with your actual API URL
    this.http.get<any[]>('your-api-endpoint-here')
      .subscribe({
        next: (data) => {
          // Grab the first 10 items (in case the API returns more than we need)
          this.originalData = data.slice(0, 10);
          // Initialize the displayed content with these 10 items
          this.content = [...this.originalData];
        },
        error: (err) => {
          console.error('Oops, failed to fetch data:', err);
        }
      });
  }

  getData(): void {
    // Append the original 10 items to the existing content list
    this.content = [...this.content, ...this.originalData];
  }
}

Step 2: Tweak the Template (app.component.html)

Your existing template is nearly perfect—just a small semantic adjustment to keep the button outside the repeating list:

<div>
  <ul>
    <li *ngFor="let item of content">{{item.name}}</li>
  </ul>
  <button class="load-more" (click)="getData()">Load More</button>
</div>

Quick Key Notes:

  • originalData variable: This holds the initial 10 items permanently, so we don't waste API calls re-fetching the same data every time the button is clicked.
  • fetchInitialData(): Runs when the component first loads, grabs the API data, slices it to 10 items, and sets up both our source data and initial displayed content.
  • getData(): Uses spread syntax to append the original items to the current content array—Angular automatically detects this change and updates the UI.

Don't forget to add HttpClientModule to your app module (so the HttpClient works):

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // ... other imports
    HttpClientModule
  ],
  // ...
})
export class AppModule { }

内容的提问来源于stack exchange,提问作者Archana R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:02:32