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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:05:46  来源:igfitidea点击:

Using ngIf without an extra element in Angular 2

htmltemplatesangular

提问by janispritzkau

Can I use ngIfwithout 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-containeris preferred over template:

ng-container优先于template

<ng-container *ngIf="expression">

See:

看:

Angular 2 ng-container

Angular 2 ng-容器

https://github.com/angular/angular.io/issues/2303

https://github.com/angular/angular.io/issues/2303

回答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 *ngIfwith [ngIf]like this.

您可以简单地使用<template>标签并替换*ngIf[ngIf]这样。

<template [ngIf]="...">
  ...
</template>

回答by Pankaj Parkar

You can't put divdirectly inside tr, that would make invalid HTML. trcan only have td/th/tableelement 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 *ngForover tbody& have ngIfover tritself like below.

你可能会略有不同的HTML有*ngFortbody与有ngIftr低于自己喜欢。

<tbody *ngFor="...">
  <tr *ngIf="...">
    ...
  </tr>
  <tr  *ngIf="!...">
    ...
  </tr>
  ..
</tbody>