Angular [ngForOf]的用法是什么 [英] What is Angular [ngForOf] usage
问题描述
我正在处理的一个项目中包含以下代码.您能告诉我它的作用吗?我知道*ngFor
和*ngIf
,但是这些[ngForOf]="topicdata"
和ngFor let-topic
是什么?我可以用更好的方式简化下面的代码吗?
One of a project where I'm handling is having below code.Can you tell me what it does? I know about *ngFor
and *ngIf
.But what are these [ngForOf]="topicdata"
and ngFor let-topic
? Can I simplify below code in a better way?
<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>
但是随后显示此错误:
[角度]一个元素不能有多个模板绑定.使用 只有一个名为'template'或以*
[Angular] Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *
推荐答案
The *ngFor
directive is something Angular calls microsyntax. Microsyntax essentially gives developers a way of configuring a directive in a more compact and simple way. You can see that something is using the microsyntax for the preceding *
.
代码:
<topic *ngFor="let topic of topicdata"> </topic>
例如等于:
<ng-template ngFor let-topic [ngForOf]="topicdata">
<topic> ... </topic>
</ng-template>
就像您在问题中遇到的例子一样.
Like in the example you have in your question.
简而言之-您可以将代码替换为*ngFor="let topic of topicdata"
并获得相同的结果.
So in short - you can replace you code with *ngFor="let topic of topicdata"
and get the same result.
编辑-要修复:* ng如果在同一行
Angular不允许您在同一元素上使用两个或多个结构指令.因此,作为在同一行上使用*ngIf
的一种方式,我建议循环出一个<ng-container>
元素,并将您的<topic>
放入该元素中.
Angular doesn't allow you to use two or more structural directives on the same element. So as a way of using *ngIf
on the same line I recommend looping out an <ng-container>
element and put your <topic>
inside that one.
<ng-container *ngFor="let topic of topicdata">
<topic *ngIf="topic.num_of_definitions > 0"> ... </topic>
<ng-container>
有关ng-container
的更多信息,> 此处
More in on ng-container
here
这篇关于Angular [ngForOf]的用法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!