angular - 在 Angular 中显示/隐藏子组件的推荐方法是什么?
问题描述
这个问题类似于这个问题,但那里没有明确的答案,它与 React 相关,而不是 Angular,所以答案可能会有所不同。本质上,问题是“从 DOM 中添加/删除元素是否优于显示/隐藏它们?” 鉴于:
<app-parent>
Zero or one of many child components displayed here.
</app-parent>
如果每个孩子都将自己包裹在一个模态中:
<app-modal visible="isVisible"> Child n's content here </app-modal>
这两种方法中的哪一种是推荐的 Angular 方法?
a. <app-parent>
<app-child1></app-child1>
<app-child2></app-child2>
</app-child>
在 parent.component.ts 文件中:
@ViewChild (Child1Component) child1: Child1Component;
...
showChild(childNumber: number) => {
if (childNumber === 1) {
this.child1.isVisible = true
} else {
this.child2.isVisible = true
}
}
(isVisible 将设置为 false,以隐藏子组件本身的模式和组件)。
或者
b. <app-parent>
<app-child1 *ngIf="showchild1"></app-child1>
<app-child2 *ngIf="showchild2"></app-child2>
</app-child>
在 parent.component.ts 文件中:
showChild(childNumber: number) => {
if (childNumber === 1) {
this.showChild1 = true
} else {
this.showChild2 = true
}
}
在案例“a”中,两个/所有子组件都被安装和渲染、隐藏,并且在满足条件之前不显示。在案例“b”中,当满足条件时,一个子组件被插入到 DOM 中,可见,并相应地删除(该部分未显示)。
推荐的 Angular 方式是什么?child/ren 组件的大小是否成为决定因素?
解决方案
选择选项 b。因为这种方式组件将在每次显示时重新初始化,否则会被销毁,并且由于更改检测而保存一些重新渲染。除非您希望组件只创建一次。
还要指出:我认为选项 a 需要 ContentChild 而不是 ViewChild。
推荐阅读
- ruby-on-rails - Ransack 是否有办法实现令牌搜索
- r - 如何使用汽车包版本 3 在 scatterplot() 中使用图例参数
- php - 如何使用 php 在输入标签中使用条件?
- python - Pandas:将列值与字典键进行比较并更新新列中的值
- python - 为什么空列表在 Python 的 while 循环中计算为 False
- apache-spark - Spark SQL 是否会一直检查所有分区的信息,甚至指定分区?
- xaml - xaml ControlTemplate 中的 TemplateBinding 不起作用
- html - HTML“字体”标签正在使用基因组数据创建空白
- ios - 如何缩放视图的所有组件?
- java - 如何验证 RestAPI 控制器端点的 RequestHeader