Aaa
Aaa

Reputation: 23

load more data on click in angular 8

<ng-container *ngFor="let data of dataList">
<mat-checkbox">{{data}}</mat-checkbox>
</ng-container>

I have to display 3 checkbox for data initally then on click 3 more data to display respectively on click until the length of datalist . I am using angular material and angular 8 .

Upvotes: 0

Views: 6055

Answers (2)

Eddy Sumra
Eddy Sumra

Reputation: 26

In the component, we will store a reference to the entire data, and then a sliced version of it, that will represent the data to be displayed.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  private data = [1,2,3,4,5,6,7,8,9,0]; 
  displayData = [1,2,3]; 
 
  showMore() {
    let newLength = this.displayData.length + 3;
    if (newLength > this.data.length) {
        newLength = this.data.length
    }
     this.displayData = this.data.slice(0, newLength);
  }

}

component.html

<ng-container *ngFor="let data of displayData">
  <button>{{data}}</button>
</ng-container>

<div>
  <button (click)="showMore()">Show More</button>
</div>

Did not setup material for this, but should be able to replace the buttons tags with mat-checkbox

Upvotes: 1

Rebai Ahmed
Rebai Ahmed

Reputation: 1600

For the initial display of the first 3 elements, you can use the SlicePipe provided by Angular : (update) : I just updated my answer , check this solution

 <ng-container *ngFor="let data of tmpData ">
    <mat-checkbox">{{data}}</mat-checkbox>
    </ng-container>

Component.ts :

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
    
      dataList = [1,2,3,4,5,6,7,8,9,0]; 
      tmpData = []; 

  ngOnInit() {
    this.tmpData =this.dataList.(0,3)
  }
     
      showMore() {
        let newLength = this.displayData.length + 3;
        if (this.dataList.length >0) {
            this.tmpData.push(this.dataList.(0,3))
        }
      }
    
    }

Upvotes: 0

Related Questions