【问题标题】:How to loop with multiple *ngFor with different div - Angular 5如何循环使用具有不同 div 的多个 *ngFor - Angular 5
【发布时间】:2019-02-28 00:06:02
【问题描述】:

我对此 json 层次结构(内容 -> 类别 -> 项目)有响应,内容包含类别对象,每个类别都包含项目对象。所以我尝试了这个:

<div *ngFor="let content of data">
    <span>{{content.name}}</span>
    <div *ngFor="let category of content.categories">
        <span>.....</span>
    </div>
</div>
<div *ngFor="let item of category.items">
    <span>{{item.type}}</span> //this item is undefined because it is out of category looping div
</div>

【问题讨论】:

  • ..问题是?那你为什么不把它搬进去呢?
  • 你在问什么?你有什么顾虑
  • 我已经更新了我的答案,请看一下
  • 你想用嵌套 fors 之外的 ngfor 来完成什么?根据您的描述,您没有categories 对象,只有content.categories。那么您希望看到哪些内容不能放在循环中?
  • 因为content.categories 也是一个数组,而category 是对每个循环中的其中一个元素的引用,您希望在content.categories 数组的哪个实例或元素中迭代&lt;div *ngFor="let item of category.items"&gt;...&lt;/div&gt; 循环?

标签: angular ngfor


【解决方案1】:

将项目的 for 循环也放在遍历类别的 div 中。如果您希望这个 div 不在该类别中,那么您还必须在那里创建更多循环。

<div *ngFor="let content of data">
    <span>{{content.name}}</span>
    <div *ngFor="let category of content.categories">
        <span>.....</span>    
         <div *ngFor="let item of category.items">
               <span>{{item.type}}</span> //this item is undefined because it is out of category looping div
         </div>
    </div>
</div>

其他循环之外的类别:

<div *ngFor="let content of data">
  <span>{{content.name}}</span>
  <div *ngFor="let category of content.categories">
    <span>.....</span>
  </div>
</div>
<div *ngFor="let content of data">
  <div *ngFor="let category of content.categories">
    <div *ngFor="let item of category.items">
      <span>{{item.type}}</span>
    </div>
  </div>
</div>

【讨论】:

  • 外面需要,我知道里面就好了
【解决方案2】:

*ngFor 对象的范围在结束标记之内而不是在结束标记之外,所以为了实现这一点,您可以使用 ng-template

你可以这样做,

<ng-template let-content ngFor [ngForOf]="data">

   <span>{{content.name}}</span>
   <ng-template let-category ngFor [ngForOf]="content.categories">
      <span>{{category.name}}</span>

      <div *ngFor="let item of category.items">
        <span>{{item.name}}</span>
      </div>
    </ng-template>

</ng-template>

.ts

data = [{
     categories: [{
       name: 'xyz',
        items: [{
          name: 'item1'
        }]
     }]
   }];

【讨论】:

    【解决方案3】:

    根据@Teun 中的帖子评论,我认为你想要:

    <div *ngFor="let content of data">
      <span>{{content.name}}</span>
      <div *ngFor="let category of content.categories">
        <span (click)="selectedCategory = category">.....</span>
      </div>
    </div>
    <div *ngIf="selectedCategory !== undefined">
      <div *ngFor="let item of selectedCategory">
        <span>{{item.type}}</span>
      </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-12
      • 2018-04-09
      • 2016-07-16
      • 2022-07-06
      • 2019-06-12
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      相关资源
      最近更新 更多