我应该直接在组件上使用Angular ngIf吗?

时间:2018-01-29 20:48:51

标签: angular

我是Angular的新手,已经习惯了基础知识。

如果我有一个我想要显示或隐藏的组件,具体取决于变量 我应该在组件本身上使用* ngIf还是在组件内部使用内容。

例如,如果变量照片为真,则会加载组件“照片”组件

<photos *ngIf="photos"></photos>

Eg.2组件的内容 照片组件始终存在,但内容已加载

<section class="photos-content" *ngIf="photos"> // content here </section>

1 个答案:

答案 0 :(得分:2)

如果你在html元素上使用*ngIf指令(例如2),那么这个元素将在DOM中创建。太多的html元素并不是那么好。你的页面会很慢。所以第一个例子(例如1)更好。

否则,您可以使用<ng-container></ng-container>扩展您的第二个示例:

<ng-container *ngIf="photos">
  <section class="photos-content">
    // content here
  </section>
</ng-container>

ng-container未在DOM中显示。

关于ng-container的更多说明,您可以在this上找到一个好的答案,这里有一个简短的摘要:

  

<ng-container>是一个逻辑容器,可用于对节点进行分组,但不会在DOM树中呈现为节点。

     

<ng-container>呈现为HTML评论。

以下是

的示例

此角度代码:

<div>
    <ng-container>fooText</ng-container>
<div>

将在您的html文件中生成此评论:

<div>
    <!--template bindings={}-->fooText
<div>

详细了解ng-container here