angular2 中的 Ng-repeat-start - 也就是使用 NgFor 重复多个元素 [英] Ng-repeat-start in angular2 - aka repeat multiple elements using NgFor
问题描述
我需要在 Angular2 的列表中为每个项目重复几个 li
元素.在 angular 1.x 中,我为此使用了 ng-repeat-start
和 ng-repeat-end
.我在 Angular 2 中找不到正确的方法.有一些较旧的博客文章 关于这一点,但他们的建议在 Angular2 的最新测试版中不起作用.
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.
所有 元素都应该为每个类别重复:(我通常会使用属性
*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
Victor Savkin> 和 模板
:
According to Victor Savkin on ngFor
and templates
:
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>
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屋!