【问题标题】:Angular reuse component in another position in dom WITHOUT reinitializationdom中另一个位置的角度重用组件,无需重新初始化
【发布时间】:2021-06-25 16:48:49
【问题描述】:

在我们的 Angular (v11) 应用程序中,我们在 DOM 的不同位置多次使用某些组件,并使用 ngIf 切换它们的输入/输出。主要是因为响应式设计决策。示例:

<comp1 ngIf*="mobile">

...在另一个位置,可能在其他一些组件中:

<comp1 ngIf*="desktop">

当我们切换视图时,这种情况下Angular的默认行为是,从dom中的位置1移除标签,组件将被杀死,标签被添加到dom中的其他位置2,组件将被重新初始化再次。

我们能否在不改变任何组件的情况下,在 DOM 中的另一个位置重用这个组件?

【问题讨论】:

标签: angular


【解决方案1】:

如果你不想触发组件生命周期,那么使用ngClass并用css定义你的定位规则呢?类似的东西

<div [ngClass]="isMobile ? 'mobile' : 'desktop'"></div>

和你的CSS:

.mobile {
   top: 1px;
}

.desktop {
   top: 100px;
}

这种方式只更新外观并保留组件状态。

【讨论】:

    【解决方案2】:

    您可以使用 ngSwitchCase,Dom 会自动重新渲染,这是一个很好的衡量标准。或使用 ngClass 并使用简单的布尔逻辑将元素绑定到不同的位置,还有其他更复杂的方法可以做到这一点,但如果它只有几个位置,那么对于代码维护问题来说,更简单地做到这一点更有意义。使用 switchcase 只允许根据条件重新渲染 Dom。您还可以使用带有指令的 ngOnInit、ngOnDestory 来生成组件,这就是我们所做的 - 但如果您没有,那就需要维护很多代码。

    yourloading.component.html

    <ng-container >
    <div [ngSwitch]="deviceType">
      <div *ngSwitchCase="'desktop'"> <app-component1 [layout]="desktop"></app-component1></div></ng-container>
    </div>
    <div *ngSwitchCase="'mobile'"> <app-component1 [layout]="mobile"></app-component1></div></ng-container>
    </div>
    </div>
    </ng-container>
    

    yourloading.component.ts 在您打开组件装饰器之后

    deviceType ?: string;
    

    component1.component.ts

    //import Input
    import { Component, OnInit, Input } from '@angular/core';
    @Input() layOut ?: string;
    
    topLocation: boolean;
    bottomLocation: boolean;
    ngOnInit(){
    if(layout === 'desktop'){
       topLocation = true;
    }
    if(layout === 'mobile'){
       bottomLocation = true;
    }
    
    }
    

    component1.component.css

    .top{
    margin-top: 0;
    height: 100vh;
    width: 100vw;
    }
    .bottom {
    margin-bottom: 0;
    bottom: 0;
    height: 100vh;
    width: 100vw;
    }
    .show{
    visibility: visible;
    height: 100%;
    }
    .hide{
    visibility: none;
    height: 0;
    }
    

    component1.component.html

    <div [ngClass]="topLocation ? 'show':'hide'">
      component html cool things maybe call another component with designs or something or change other css classes
    </div>
    <div [ngClass]="bottomLocation ? 'show':'hide'">
      component html cool things
    </div>
    

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      相关资源
      最近更新 更多