【问题标题】:Angular component attributesAngular 组件属性
【发布时间】:2020-03-22 20:08:14
【问题描述】:

我是 Angular 新手,我有一个简短的问题。我查看了英雄之旅教程并完全按照它进行操作。这是一个很好的开始方式。我还完成了 Udemy 的完整 Angular 课程,但我的用例没有被讨论或解释。

我有一个组件,比如说 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>

这会显示一个列表(可能很长)。现在,我想在仪表板组件上显示最新的 5 个项目。我可以这样做吗:

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

或者类似的东西?因为《英雄之旅》教程确实在仪表板上显示了 5 个英雄的列表,但它只是复制并粘贴了相同的代码:

ToH 组件.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 仪表板:

<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>

我只是想调用我的组件,但将其限制为 5 个项目。这不可能吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以使用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>
    

    如果你希望它是动态的,你可以有一个像这样的@Input()

    @Input() limit: number;
    

    ... 在 HTML 中:

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

    用例:

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

    PS:请注意,list-itemlist-items 都不是有效的变量名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-30
      • 2017-07-30
      • 2016-09-23
      • 2018-12-16
      • 1970-01-01
      • 2020-03-22
      • 2019-05-05
      相关资源
      最近更新 更多