Angular2中的Ng-repeat-start-也使用NgFor重复多个元素 [英] Ng-repeat-start in angular2 - aka repeat multiple elements using NgFor
问题描述
我需要为每个项目在Angular2的列表中重复几个li
元素.在角度1.x中,我为此使用了ng-repeat-start
和ng-repeat-end
.我在Angular 2中找不到正确的方法.有一些较早的博客文章 a>关于此问题,但他们的建议在最新的Angular2 Beta中不起作用.
I need to repeat several li
-elements in a list in Angular2 for each item. In angular 1.x I used ng-repeat-start
and ng-repeat-end
for this. I can't find the right way to do it in Angular 2. There are some older blog posts about this, but their suggestions don't work in the newest beta of Angular2.
对于每个类别,应重复所有<li>
元素:
(我通常会使用属性*ngFor="#category of categories"
进行操作-但我找不到放置它的位置...
All <li>
-elements should be repeated for each category:
(which I would normally do with the attribute *ngFor="#category of categories"
- but I can't find where to put it...
帮助?
<ul class="dropdown-menu" role="menu">
<li class="dropdown-header">
{{ category.title }}
</li>
<li>
<a href="{{ '/music/' + tag.keyword }}" *ngFor="#tag of category.tags" [hidden]="tag.deleted === 1">{{ tag.tag_title_da }}</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Alle musikstykker</li>
<li><a href="/music/all">Alle musikstykker</a></li>
</ul>
推荐答案
如果要重复内容,请使用template
标记,并删除ngFor
上的*
前缀.
If you want to repeat the contents, use the template
tag, and remove the *
prefix on ngFor
.
根据ngFor
和templates
上的 Victor Savkin :
Angular以特殊方式对待模板元素.他们习惯了 创建视图,可以动态操纵的DOM块.这 * 语法是一种快捷方式,可让您避免编写整个 元素.
Angular treats template elements in a special way. They are used to create views, chunks of DOM you can dynamically manipulate. The * syntax is a shortcut that lets you avoid writing the whole element.
<ul class="dropdown-menu" role="menu">
<template ngFor #category [ngForOf]="categories">
<li class="dropdown-header">
{{ category.title }}
</li>
<li>
<a href="{{ '/music/' + tag.keyword }}" *ngFor="#tag of category.tags" [hidden]="tag.deleted === 1">{{ tag.tag_title_da }}</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Alle musikstykker</li>
<li><a href="/music/all">Alle musikstykker</a></li>
</template>
</ul>
更新角度^ 2.0.0
您可以使用ng-container
,只需将#var
更改为let var
.
You can use ng-container
and just change #var
to let var
.
<ng-container>
的行为与<template>
相同,但允许使用更通用的语法.
<ng-container>
behaves the same as the <template>
but allows to use the more common syntax.
<ul class="dropdown-menu" role="menu">
<ng-container *ngFor="let category of categories">
<li class="dropdown-header">
{{ category.title }}
</li>
<li>
<a href="{{ '/music/' + tag.keyword }}" *ngFor="let tag of category.tags" [hidden]="tag.deleted === 1">{{ tag.tag_title_da }}</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Alle musikstykker</li>
<li><a href="/music/all">Alle musikstykker</a></li>
</ng-container>
</ul>
这篇关于Angular2中的Ng-repeat-start-也使用NgFor重复多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!