R-b-n
R-b-n

Reputation: 513

Angular component attributes

I have a quick question as I am an Angular newbie.. I looked at the Tour Of Heroes tutorial and followed it exactly. It was a great way of getting started. I also finished the Complete Angular course from Udemy, but my use case is discussed nor explained in neither.

I have a component, let's say array-list.component.html:

<div class="list-group list-group-flush dl-list-group" *ngIf="listitems">
  <ul class="list-group">
    <li
      class="list-group-item"
      style="cursor: pointer"
      *ngFor="let list-item of list-items; let i = index"
      (click)="onEditListItem(i)"
    >
      {{ list-item.name }} ({{ list-item.date }})
    </li>
  </ul>
</div>

This displays a list (can be a very long one). Now, I want to have the latest 5 items on my dashboard component. Can I do this:

<app-array-list items=5></app-array-list>

Or something like that? Because the Tour of Heroes tutorial does show a list of 5 heroes on the dashboard, but it simply copies and paste the same code:

ToH component.html:

<ul class="heroes">
    <li *ngFor="let hero of heroes" (click)="onSelect(hero)"
        [class.selected]="hero === selectedHero">
        <span class="badge">{{hero.id}}</span>
        <span>{{hero.name}}</span>
        <button class="delete"
                (click)="delete(hero); $event.stopPropagation()">x
        </button>
    </li>
</ul>

ToH dashboard:

<div class="grid grid-pad">
    <a *ngFor="let hero of heroes" [routerLink]="['/detail', hero.id]" class="col-1-4">
     <div class="module hero">
      <h4>{{hero.name}}</h4>
     </div>
    </a>
</div>

I simply want to call my component but limit it to let's say 5 items.. Is this not possible?

Upvotes: 1

Views: 63

Answers (1)

developer033
developer033

Reputation: 24894

You could use the SlicePipe:

<div class="list-group list-group-flush dl-list-group" *ngIf="items">
  <ul class="list-group">
    <li
      class="list-group-item"
      style="cursor: pointer"
      *ngFor="let item of items | slice: 0: 5; index as i"
      (click)="onEditListItem(i)"
    >
      {{ item.name }} ({{ item.date }})
    </li>
  </ul>
</div>

If you want it to be dynamic, you can have an @Input() like this:

@Input() limit: number;

... and in HTML:

*ngFor="let item of items | slice: 0: limit; index as i"

Use case:

<app-array-list [limit]="5"></app-array-list>

PS: Note that neither list-item nor list-items are valid variable names.

Upvotes: 1

Related Questions