我正在处理的一个项目有下面的代码。你能告诉我它的作用吗?我知道关于*ngFor
and *ngIf
.但是这些是什么[ngForOf]="topicdata"
and ngFor let-topic
?我可以以更好的方式简化下面的代码吗?
<ng-template ngFor let-topic [ngForOf]="topicdata">
<topic *ngIf="topic.num_of_definitions>0" [data]="topic"></topic>
</ng-template>
我想要它如下所示。
<topic *ngFor="let topic of topicdata" [data]="topic"
*ngIf="topic.num_of_definitions>0"></topic>
但随后它显示此错误:
[Angular] 一个元素上不能有多个模板绑定。使用
只有一个名为“template”或以 * 为前缀的属性
The *ngFor
指令是 Angular 调用的东西微语法 https://angular.io/guide/structural-directives#microsyntax. 微语法本质上为开发人员提供了一种以更紧凑和简单的方式配置指令的方法。您可以看到某些内容正在使用前面的微语法*
.
代码:
<topic *ngFor="let topic of topicdata"> </topic>
例如将等于:
<ng-template ngFor let-topic [ngForOf]="topicdata">
<topic> ... </topic>
</ng-template>
就像你问题中的例子一样。
简而言之 - 你可以用以下代码替换你的代码*ngFor="let topic of topicdata"
并得到相同的结果。
编辑 - 修复:*ngIf 在同一行
Angular 不允许您使用两个或多个结构指令在同一个元素上。所以作为一种使用方式*ngIf
在同一行我建议循环出一个<ng-container>
元素并把你的<topic>
在那里面。
<ng-container *ngFor="let topic of topicdata">
<topic *ngIf="topic.num_of_definitions > 0"> ... </topic>
<ng-container>
更多内容请关注ng-container
here https://angular.io/guide/structural-directives#ngcontainer
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)