3

I am currently working on a project in Angular 7 with Typescript an am trying to optimise the following (simplified) code snippet:

<div *ngIf="!showAll">

  <div *ngFor="let filter of filters | slice:0:5;">
    <mat-checkbox [checked]="filter.selected">{{ filter.value }}</mat-checkbox>
  </div>

</div>

<div *ngIf="showAll">

  <div *ngFor="let filter of filters">
    <mat-checkbox [checked]="filter.selected">{{ filter.value }}</mat-checkbox>
  </div>

</div>

If the boolean showAll is true, I want to show all values of my filters array, if it isn't I want to slice this array to only get the first 5 entries. Is this possible in one line of code?

hY8vVpf3tyR57Xib
  • 3,574
  • 8
  • 41
  • 86

2 Answers2

3

You can use ngIf with multiple conditions to achieve that.

  <div *ngFor="let filter of filters ; let i = index">
    <mat-checkbox *ngIf="showAll || i < 5" [checked]="filter.selected">{{ filter.value }}</mat-checkbox>
  </div> 
hY8vVpf3tyR57Xib
  • 3,574
  • 8
  • 41
  • 86
NTP
  • 4,338
  • 3
  • 16
  • 24
1

Try this

 <div *ngFor="let filter of showAll ? filters : (filters | slice:0:5) ">
    <mat-checkbox [checked]="filter.selected">{{ filter.value }}</mat-checkbox>
  </div>
dileepkumar jami
  • 2,185
  • 12
  • 15