Press the 'display additional' option within ngFor in Angular 2

I have a long list of more than 50 items that I need to display. What I want to do is show only the first 10 items initially, and then when a button is clicked, reveal the next 10 items, and keep repeating this process until all items are shown.

<ul class="results-main-content">
  <li class="right-results-section">
    <ul class="_result-list">
      <li class="result" *ngFor="let searchResult of searchResults">
        {{searchResult.name}}
      </li>
    </ul>
  </li>
  <li class="showmore">
    <button class="show-more">
      <img class="more" src="_arrow-down.svg" alt="" />
    </button>
  </li>
</ul>

Would it be possible to implement this functionality in angular2?

If anyone has any insights or solutions to offer, please share with me and the wider SO community.

Thank you

Answer №1

To limit the number of items displayed, you can utilize the slice pipe:

show = 5;
<li *ngFor="let searchResult of searchResults|slice:0:show let i=index">
  {{searchResult.name}}
  <button *ngIf="i==4 && show == 5" (click)="show = searchResults.length">Show More</button>
</li>

Check out this Plunker example

Related resources:

  • How to display only one item in ngFor loop in Angular?

Answer №2

By adapting Günter Zöchbauer's code, you can achieve the desired functionality by referring to this sample

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
<ul>  
 <li *ngFor="let tag of tags | slice:0:show; let i=index">
  <a href="#" class="span-tag tag">{{ tag }}</a>
 </li>
<div *ngIf="show < tags.length" (click)="increaseShow()">DropDown Button</div>
</ul>
`,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  show = 10;
  tags = ['a','b','c','d','e','f','g','h','i','j','a','b','c','d','e','f','g','h','i','j', 'a','b','c','d','e','f','g','h','i','j','a','b','c','d','e','f','g','h','i','j', 'a','b','c','d','e','f','g','h','i','j'];

  increaseShow() {
   this.show += 10; 
 }
}

Check out the example on StackBlitz

Answer №3

Below is the recommended code snippet for your reference:

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <ul class="results-main-content">
  <li class="right-results-section">
    <ul class="_result-list">
      <li class="result" *ngFor="let item of content">
        {{item.colorName}}
      </li>
    </ul>
  </li>
  <li class="showmore">
    <button class="show-more" (click)="getData()" [disabled]="counter>=content.length">
      Show more
    </button>
  </li>
</ul>
    </div>
  `,
})
export class App {
  name:string;
  data = [...]; // refer plunker
  content:any[]=new Array();
  counter:number;
  constructor() {
    this.counter=0;
    this.getData();
    this.name = 'Angular2'
  }
  getData(){
    console.log(this.counter + 'dat size'+this.data.length)

    for(let i=this.counter+1;i<this.data.length;i++)
    {
    this.content.push(this.data[i]);
    if(i%10==0) break;
    }
    this.counter+=10;

  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

LIVE DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering checkbox selection in Angular reactive formsLearn how to effortlessly manage the checked status of

I am struggling with setting the checked status of a checkbox control within an Angular reactive form. My goal is to change the value based on the checked status, but it seems like the value is controlling the status instead. For instance, I want the for ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

Azure Function responding with a 401 error code upon passing parameters through a proxy

I have a situation where I am working with an Angular service that includes a GET request with parameters currentPage and postsPerPage. In my efforts to pass these parameters to an Azure function, I came across a tutorial advising me to set up proxies. Wh ...

Exploring the capabilities of the VSCode Volar extension in a project utilizing Vue 2, Nuxt, Typescript, and the @nuxtjs composition-api

Trying to set up the Volar VSCode extension for a NuxtJS / Typescript project and facing two issues in .vue file templates. Followed the installation guide for Vue 2 and Typescript, and enabled Take Over mode. Solved some codebase issues with the extensio ...

Tips for successfully sending a variable through setOnClickListener

Overview: The main layout, map_midvalley_g, contains 8 image buttons that can be clicked. Using a for loop on the data retrieved from the server, the color (green or red) of the image buttons is set. Clicking on any of the image buttons will trigger a popu ...

Retrieving variables from JavaScript files in TypeScript

Greetings, I am in the process of upgrading an existing Angular application from version 2 to 9. My approach involves first moving it to angular 4 and then continuing with the upgrades. I have successfully updated the necessary packages, but now I'm e ...

Creating Geometric Artwork with a Button (Python Tkinter)

Can a button be linked to a function that creates a shape on the canvas? Here is an excerpt of the code in question: def option(*args): global missguess missguess=missguess+1 if missguess==1: w.create_oval(210,100,295,175,width=3) if missguess==2: ...

Exploring the sharing of observables/subjects in Angular 2

UPDATE: After further investigation, it appears that the SharedService is being initialized twice. It seems like I may be working with separate instances, causing the .subscribe() method to only apply to the initiator. I'm not sure how to resolve this ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Can you provide an example of a valid [routerLink] for a relative auxiliary route?

Suppose I have the following route configuration: { path: 'contact', component: ContactComponent, children: [ { path: ':id', component: ContactDetailComponent }, { path: 'chat', component: ContactChatComponent, outlet ...

The functionality to automatically close the Material Sidebar upon clicking a navigation item is not functioning properly

After navigating by clicking on Sidebar nav items, I am trying to auto close the Material Sidebar. However, it doesn't seem to work in that way for me. I have created a Stackblitz to demonstrate my issue: Access the Stackblitz Editor Site here: http ...

Angular 7.3.9 encountered an issue: ERROR ts(37,44): error TS1109 - An expression was expected but

I've encountered an issue with my code in Angular 7.3.9, here's the snippet; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; import { ToastrService } fr ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

Having trouble accessing Vuex's getter property within a computed property

Can you help me troubleshoot an issue? When I call a getter inside a computed property, it is giving me the following error message: TS2339: Property 'dictionary' does not exist on type 'CreateComponentPublicInstance{}, {}, {}, {}, {}, Com ...

Can *ngFor in Angular handle asynchronous rendering?

Within the code snippet provided, the line this.images = response.map( r => r.url).slice(0,10); populates the images array. The data is then rendered in the view using ngFor. Following this, a jQuery function is invoked to initialize an image slider. Ho ...

Issue with e2e.js file format in Cypress Support

I am trying to save Cypress screenshots into a report using a support file as recommended in the documentation. However, I keep encountering an error: Your supportFile is missing or invalid: support/e2e.js The supportFile must be a .js, .ts, .coffee file ...

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...