Angular2 ngIf在false时创建空元素

时间:2017-05-11 11:42:57

标签: javascript angular typescript ngif

我遇到Anguar2和ngIf的问题:

我有一个从数组创建表的代码(DIY编码偏移量为6):

RxJava/RxAndroidSchedulersHook

问题是,angular会在其中创建一个带有此注释的空tr:

<table class="table2">
  <tr>
    <th>Raum</th>
    <th>Ticket</th>
  </tr>
  <tr *ngFor="let a of aufrufe | async; let odd = odd; let i = index" [@newsState]="anistate[a.appid]" (click)="switchState(a)">
    <ng-container *ngIf="a.room != 'Beratungsplatz' && i > 7 ">
      <ng-container *ngIf="odd">
        <td class="roomodd">{{a.room}}</td>
        <td class="ticketodd">{{a.ticket}}</td>
      </ng-container>
      <ng-container *ngIf="!odd">
        <td class="room">{{a.room}}</td>
        <td class="ticket">{{a.ticket}}</td>
      </ng-container>
    </ng-container>
  </tr>
</table>

那“摧毁”了我的风格。第一个容器中的ngIf不应该打印,如果它是假的吗?(索引&gt; 7)

提前谢谢!

3 个答案:

答案 0 :(得分:1)

尝试对<ng-container>使用*ngFor,并在第一个<tr>

内时仅包含*ngIf
<ng-container *ngFor="let a of aufrufe | async; let odd = odd; let i = index" >
  <ng-container *ngIf="a.room != 'Beratungsplatz' && i > 7 ">
    <tr [@newsState]="anistate[a.appid]" (click)="switchState(a)">
      <ng-container *ngIf="odd">
        <td class="roomodd">{{a.room}}</td>
        <td class="ticketodd">{{a.ticket}}</td>
      </ng-container>
      <ng-container *ngIf="!odd">
        <td class="room">{{a.room}}</td>
        <td class="ticket">{{a.ticket}}</td>
      </ng-container>
    </tr>
  </ng-container>
</tr>

答案 1 :(得分:0)

明显的答案是将*ngIf*ngFor放在<tr>上,但这是不可能的。

我的建议是制作一个管道,用于过滤条件a.room != 'Beratungsplatz' && i > 7下的所有记录。这样,您只会打印需要存在的元素。

示例:

<强>管

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'rooms'
})

export class RoomsFilter implements PipeTransform {
    transform(value: any, roomName: string, index: number, allowedValue: number ): any {
        return room != roomName && index > allowedValue ;
    }
}

<强> HTML

...
<tr *ngFor="let a of aufrufe | async | rooms: a.room: 'Beratungsplatz': i : 7; let odd = odd; let i = index" [@newsState]="anistate[a.appid]" (click)="switchState(a)">
    <ng-container *ngIf="odd">
        <td class="roomodd">{{a.room}}</td>
        <td class="ticketodd">{{a.ticket}}</td>
    </ng-container>
    <ng-container *ngIf="!odd">
        <td class="room">{{a.room}}</td>
        <td class="ticket">{{a.ticket}}</td>
    </ng-container>
</tr>
...

答案 2 :(得分:0)

尝试使用模板

<table class="table2">
  <tr>
    <th>Raum</th>
    <th>Ticket</th>
  </tr>
  <template ngFor let-a [ngForOf]="aufrufe | async" let-i=index [@newsState]="anistate[a.appid]" (click)="switchState(a)">
  <tr *ngIf="a.room != 'Beratungsplatz' && i > 7 ">
    <ng-container>
      <ng-container *ngIf="odd">
        <td class="roomodd">{{a.room}}</td>
        <td class="ticketodd">{{a.ticket}}</td>
      </ng-container>
      <ng-container *ngIf="!odd">
        <td class="room">{{a.room}}</td>
        <td class="ticket">{{a.ticket}}</td>
      </ng-container>
    </ng-container>
  </tr>
 </template>
</table>