首页 > 解决方案 > 在 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 组件的大小是否成为决定因素?

标签: angulardomhtml-rendering

解决方案


选择选项 b。因为这种方式组件将在每次显示时重新初始化,否则会被销毁,并且由于更改检测而保存一些重新渲染。除非您希望组件只创建一次。

还要指出:我认为选项 a 需要 ContentChild 而不是 ViewChild。


推荐阅读