Search code examples
angularbuttontypescriptshow-hidengfor

Show more button in ngFor in angular2


I have a list of over 50 items. I would like to show only the first 10 items, and I would have a button that when clicked shows the next 10 items, and which clicked again, the next 10 items until all is 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>

Is this possible to achieve in angular2?

If so, please enlighten me and the SO community.

Thanks


Solution

  • You should use the below code

    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