首页 > 解决方案 > ngFor 基于类型

问题描述

现在它打印两次没有数据。我只想替换没有数据的第三个,因为数组中不存在类型 3。

所以我的条件是有时我得到类型为 3 或类型 2 或类型 1 的数组,如果数组没有类型 3 或类型 2 或类型 1,那么只打印一次。

其实我没有办法做:(

堆栈闪电战:https ://stackblitz.com/edit/angular-r85hhs?file=src%2Fapp%2Fapp.component.html

app.component.html

<ng-container *ngFor="let item of test">
 <ng-container *ngIf="item.type === 1">
   <p>  {{item.name}}</p>
 </ng-container>
 <ng-container *ngIf="item.type === 2">
   <p>  {{item.name}}</p>
 </ng-container>
 <ng-container *ngIf="item.type === 3">
    <p>{{item.name}}</p>
 </ng-container>
<ng-container *ngIf="item.type !== 3">
NO data
</ng-container> 
</ng-container>

app.component.ts

  public test = [{type:1, name:'shawn'},
   {type:2, name:"ronny"}
  ]

在此处输入图像描述 谢谢

标签: angular

解决方案


更新到这个

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>
<hr />
<div *ngIf="test?.length > 0">
  <ng-container *ngFor="let item of test">
    <ng-container *ngIf="item.type === 1">
      <p>{{ item.name }}</p>
    </ng-container>
    <ng-container *ngIf="item.type === 2">
      <p>{{ item.name }}</p>
    </ng-container>
    <ng-container *ngIf="item.type === 3">
      <p>{{ item.name }}</p>
    </ng-container>
  </ng-container>
</div>
<div>
   <ng-container *ngIf="item?.length === 0">NO data</ng-container>
</div>

推荐阅读