问题描述
我们不能在同一元素上使用 * ngFor
和 * ngIf
.一种技术是嵌套它们.几乎所有地方都可以,除了在表中希望同时遍历 tr
并有条件地打印它们的情况之外.
We can't use *ngFor
and *ngIf
on the same element. A technique is to nest them. Almost everywhere it's OK, except in tables when we want to both loop over tr
and print them conditionally.
此处建议,我们应该使用<模板> ,或 < ng-template>
元素,这样就不会将其打印到DOM.
As suggested here we should use <template>
, or <ng-template>
elements, so that it won't be printed to the DOM.
但是我无法使其正常工作.它根本不打印任何内容.这里是一个显示它实际效果的工具a>.
But I can't make it work. It simply doesn't print out anything. Here's a plunker to show it in action.
我该怎么办?
推荐答案
由于* ngIf呈现为[ngIf],请尝试在可正常使用的模板上直接使用[ngIf].
As *ngIf is rendered as [ngIf], try using [ngIf] directly on template it should work.
HTML
<tr *ngFor="let item of items">
<ng-template [ngIf]="item.month == 12">
<td>{{ item.year }}</td>
<td>{{ item.month }}</td>
</ng-template>
</tr>
或者简单地,您可以用* ngIf
or simply you can decorate with *ngIf
<tr *ngFor="let item of items">
<div ngIf*="item.month == 12">
<td>{{ item.year }}</td>
<td>{{ item.month }}</td>
</div>
</tr>
更新了 朋克车
updated plunker
有用的 文章 关于结构指令
Useful article on Structural directives
这篇关于为什么ng-template在Angular中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!