ngFor基于类型

时间:2019-01-22 16:28:45

标签: angular

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

所以我的情况是我有时会得到类型3或类型2或类型1的数组 如果数组不具有类型3或类型2或类型1,则仅打印一次。

实际上我没有办法去做:(

stackblitz: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"}
  ]

enter image description here 谢谢

2 个答案:

答案 0 :(得分:0)

更新为此

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

答案 1 :(得分:0)

您可能想使用ngSwitch。在此示例中,当item.type不是1、2或3时,它将默认显示No DATA

<ng-container *ngFor="let item of test">
  <ng-container *ngSwitch="item.type">
    <p *ngSwitchCase="1">{{item.name}}</p>
    <p *ngSwitchCase="2">{{item.name}}</p>
    <p *ngSwitchCase="3">{{item.name}}</p>
    <p *ngSwitchDefault>No DATA</p>
  </ng-container> 
</ng-container>