Angular [ngForOf]的用法是什么 [英] What is Angular [ngForOf] usage

查看:443
本文介绍了Angular [ngForOf]的用法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的一个项目中包含以下代码.您能告诉我它的作用吗?我知道*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 *

推荐答案

*ngFor指令是Angular调用的

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 *ngIfon 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆