Html 在 Angular 2 中使用没有额外元素的 ngIf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36376001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using ngIf without an extra element in Angular 2
提问by janispritzkau
Can I use ngIf
without an extra container element?
我可以在ngIf
没有额外容器元素的情况下使用吗?
<tr *ngFor="...">
<div *ngIf="...">
...
</div>
<div *ngIf="!...">
...
</div>
</tr>
It doesn't work in a table because that would make invalid HTML.
它在表格中不起作用,因为这会使 HTML 无效。
回答by Alexander Taylor
ng-container
is preferred over template
:
ng-container
优先于template
:
<ng-container *ngIf="expression">
See:
看:
回答by janispritzkau
I found a method for that on: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template.
我找到了一种方法:https: //angular.io/docs/ts/latest/guide/template-syntax.html#!# star-template。
You can simply use the <template>
tag and replace *ngIf
with [ngIf]
like this.
您可以简单地使用<template>
标签并替换*ngIf
为[ngIf]
这样。
<template [ngIf]="...">
...
</template>
回答by Pankaj Parkar
You can't put div
directly inside tr
, that would make invalid HTML. tr
can only have td
/th
/table
element in it & inside them you could have other HTML elements.
你不能div
直接放在里面tr
,那会使 HTML 无效。tr
只能td
/ th
/table
元素在它里面与他们你可以有其他HTML元素。
You could slightly change your HTML to have *ngFor
over tbody
& have ngIf
over tr
itself like below.
你可能会略有不同的HTML有*ngFor
过tbody
与有ngIf
过tr
低于自己喜欢。
<tbody *ngFor="...">
<tr *ngIf="...">
...
</tr>
<tr *ngIf="!...">
...
</tr>
..
</tbody>