【问题标题】:Changing Arrays In ngFor (Angular2)在 ngFor (Angular2) 中更改数组
【发布时间】:2019-10-10 22:26:44
【问题描述】:

我有一个服务,它返回三个数组:allItems、someItems、otherItems。 在 appComponent 中,我得到了 switch 语句:

<div [ngSwitch]="sectionSelected">
  <p *ngSwitchCase="'someItems'">
  <app-items></app-items>
  </p>
</div>

在 itemsComponent 中,我得到了以下循环:

<div *ngFor="let item of itemsArray" class="m-1 p-1">
some code {{ items.property }}
</div>

我希望将 ngFor 中的 itemsArray 设置为 switch 语句中 case 的值。这个想法是循环遍历该选定的数组,而不是为每个具有相同 html 代码的数组生成子组件。 那可能吗?什么是最好的解决方案?

【问题讨论】:

    标签: angular


    【解决方案1】:

    假设 sectionSelected 在给定时间具有给定数组之一(allItems、someItems、otherItems)。你不需要 switch 语句。

    app.component.html

    <div>
      <p>
        <app-items [itemsArray]="sectionSelected"></app-items>
      </p>
    </div>
    

    在 ItemsComponent 中

    import { Input } from "@angular/core";
    ...
    @Input() itemsArray: any[]; // you can give the specific type to the array instead
    

    items.component.html

    <div *ngFor="let item of itemsArray" class="m-1 p-1">
     some code {{ items.property }}
    </div>
    

    【讨论】:

    • 谢谢,它帮助了我。
    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2016-11-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多