把 ngIf 放在哪里?
Where to put the ngIf?
我有一个关于 Angular 2 的 ngIf 的问题。我目前正在开发我的第一个更大的 Angular 2-App,我想知道 ngIf 的最佳定位。我认为应该有一定的一致性。关于加载子组件,这是我能想到的三个选项:
In a div
of the parent-component:
<div id="parent-component-div" *ngIf="loadChildComponent">
<app-child-component></app-child-component>
</div>
In a child-component-tag of the parent-component:
<div id="parent-component-div">
<app-child-component *ngIf="loadChildComponent"></app-child-component>
</div>
In the child-component:
<!-- parent-component -->
<div id="parent-component-div">
<app-child-component></app-child-component>
</div>
<!-- child-component -->
<div id="child-component-div" *ngIf="loadComponent">
<!-- child-component logic -->
</div>
就我个人而言,我发现自己遵循选项一,但看到了选项三的优势。但惯例是什么?有约定吗?
这当然是非常主观的,但我认为它应该根据某些条件放在显示或隐藏的元素上。
<div id="parent-component-div">
<app-child-component *ngIf="loadChildComponent"></app-child-component>
</div>
然后我们可以假设 html 的这一部分是一个模板。所以如果你把 ngIf
放在一个元素本身上,我们知道结构 ngIf
指令是如何转换的,我们最终会得到这个 DOM:
<div id="parent-component-div">
<template [ngIf]="loadChildComponent">
<app-child-component></app-child-component>
</template>
</div>
这是有道理的。如果你像这样把 ngIf
放在父 div 上:
<div id="parent-component-div" *ngIf="loadChildComponent">
<app-child-component></app-child-component>
</div>
parent-component-div
成为模板的一部分,它看起来不像你想做的那样。
第三个选项对我来说似乎最不合适,因为组件不应该关心它是否显示。如果已显示,则应继续执行其功能。
我的观点是 ngIf 的去向在很大程度上取决于谁拥有 ngIf 绑定到的变量。
如果 loadComponent 布尔值的设置是属于父组件的行为,那么您可以使用选项 2。
但如果 loadComponent 确实属于子组件,那么选项 3 更有意义。
我有一个关于 Angular 2 的 ngIf 的问题。我目前正在开发我的第一个更大的 Angular 2-App,我想知道 ngIf 的最佳定位。我认为应该有一定的一致性。关于加载子组件,这是我能想到的三个选项:
In a
div
of the parent-component:
<div id="parent-component-div" *ngIf="loadChildComponent">
<app-child-component></app-child-component>
</div>
In a child-component-tag of the parent-component:
<div id="parent-component-div">
<app-child-component *ngIf="loadChildComponent"></app-child-component>
</div>
In the child-component:
<!-- parent-component -->
<div id="parent-component-div">
<app-child-component></app-child-component>
</div>
<!-- child-component -->
<div id="child-component-div" *ngIf="loadComponent">
<!-- child-component logic -->
</div>
就我个人而言,我发现自己遵循选项一,但看到了选项三的优势。但惯例是什么?有约定吗?
这当然是非常主观的,但我认为它应该根据某些条件放在显示或隐藏的元素上。
<div id="parent-component-div">
<app-child-component *ngIf="loadChildComponent"></app-child-component>
</div>
然后我们可以假设 html 的这一部分是一个模板。所以如果你把 ngIf
放在一个元素本身上,我们知道结构 ngIf
指令是如何转换的,我们最终会得到这个 DOM:
<div id="parent-component-div">
<template [ngIf]="loadChildComponent">
<app-child-component></app-child-component>
</template>
</div>
这是有道理的。如果你像这样把 ngIf
放在父 div 上:
<div id="parent-component-div" *ngIf="loadChildComponent">
<app-child-component></app-child-component>
</div>
parent-component-div
成为模板的一部分,它看起来不像你想做的那样。
第三个选项对我来说似乎最不合适,因为组件不应该关心它是否显示。如果已显示,则应继续执行其功能。
我的观点是 ngIf 的去向在很大程度上取决于谁拥有 ngIf 绑定到的变量。
如果 loadComponent 布尔值的设置是属于父组件的行为,那么您可以使用选项 2。
但如果 loadComponent 确实属于子组件,那么选项 3 更有意义。