繁体   English   中英

Angular2 * ngIf无法正常工作

[英]Angular2 *ngIf does not work correctly

在我的代码中,im使用* 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>

图片: 显示状态的图像

使用div而不是ng-template。 您不能将语法糖*与ng-template一起使用。

结构指令

星号是“句法糖”,代表更复杂的内容。 在内部,Angular将其分为两个阶段。 首先,它将* ngIf =“ ...”转换为模板属性template =“ ngIf ...”,如下所示。

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

然后,它将template属性转换为一个元素,包裹在宿主元素中,如下所示。

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

UPDATE

就像@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>

{{收藏夹?.FavoritesIds.indexOf(internship?.InternshipId)| json}},以查看变量中的内容

我的技巧是将if语句放在单独的函数中。

===可能会在测试数字时对字符串进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM