Angular2 *ngIf 无法正常工作

Angular2 *ngIf does not work correctly

在我的代码中,我使用的是 *ngIf,它在任何时候都应该只显示两者之一。但问题是它只显示第二个,即使第二个在某些时候不应该显示。我使用 for 循环来显示所有元素,但正如您在图片中看到的那样,即使第二个的值为 -1,也只显示第二个。谢谢你的帮忙!

代码:

<ng-template let-internship="rowData" pTemplate="body" *ngIf="favorite?.FavoritesIds.indexOf(internship?.InternshipId) === -1;"><!--TODO BRIAN ngif-->
  <a class="btn btn-default" [routerLink]="['/student/stageopdrachten', internship.InternshipId, false]"><!--Not shown TODO-->
    <i class="glyphicon"></i>Meer
  </a>
</ng-template>
<ng-template let-internship="rowData" pTemplate="body" *ngIf="favorite?.FavoritesIds.indexOf(internship?.InternshipId) !== -1;"><!--TODO BRIAN ngif-->
  <a class="btn btn-default" [routerLink]="['/student/stageopdrachten', internship.InternshipId, true]"><!--always shown-->
    <i class="glyphicon"></i>Meer{{favorite?.FavoritesIds.indexOf(internship?.InternshipId)}}
  </a>
</ng-template>

图片:

做一个{{favorite?.FavoritesIds.indexOf(internship?.InternshipId) | json}} 查看变量中的内容

我的建议是将 if 语句放在单独的函数中。

有可能 === 测试字符串而它是一个数字。

使用 div 而不是 ng-template。你不能在 ng-template 中使用语法糖 *。

Structural Directives

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular desugars it in two stages. First, it translates the *ngIf="..." into a template attribute, template="ngIf ...", like this.

<div template="ngIf hero">{{hero.name}}</div>

Then it translates the template attribute into a element, wrapped around the host element, like this.

<ng-template [ngIf]="hero">
  <div>{{hero.name}}</div>
</ng-template>

更新

就像@Daniel Cooke 说的,我应该使用 div 因为 ng 模板彼此相邻时效果不佳。而是使用 divs 并且只有一个 ng 模板做到了。所以工作代码:

<ng-template let-internship="rowData" pTemplate="body" ><!--TODO BRIAN ngif -->
          <div *ngIf="favorite?.FavoritesIds.indexOf(internship?.InternshipId) === -1">
            <a class="btn btn-default" [routerLink]="['/student/stageopdrachten', internship.InternshipId, false]"><!--niet bestaat TODO-->
              <i class="glyphicon"></i>Meer
            </a>
          </div>
          <div *ngIf="favorite?.FavoritesIds.indexOf(internship?.InternshipId) != -1;">
            <a class="btn btn-default" [routerLink]="['/student/stageopdrachten', internship.InternshipId, true]"><!--wel bestaat-->
              <i class="glyphicon"></i>Meer{{favorite?.FavoritesIds.indexOf(internship?.InternshipId)}}
            </a>
          </div>
        </ng-template>