角度渲染组件首先,然后在 ng-If 中删除另一个组件

我使用ngif指令一次显示一个组件。


<app-root>

   <first-Comp *ngIf="showFirst"></first-Comp>

   <second-Comp *ngIf="!showFirst"></second-Comp>

</app-root>

要点是

  1. 显示第一变量使用 true 进行初始化。

  2. 第一合成包含高度为100px的元素;

  3. 第二比较有动态元素

在第二个组件内部,我使用内部计算高度document.body.scrollHeightngOnInit

问题是当 变为角时,首先呈现第二个合成,然后删除 .结果,我得到的高度是100+而不是0。但是我需要身体的高度,只在组件渲染。showFristfalsefirst-compsecond-comp

我错过了另一件重要的事情,因为我认为这可能不会妨碍。即第一个和第二个组件都与角度自动变化检测分离以提高性能。我有一个这样的基本组件

export class BaseComponent {

private subscriptions: Subscription[] = [];


  constructor(private childViewRef: ChangeDetectorRef) {

      this.childViewRef.detach();

  }


  public updateUI(): void {

    try {

        this.childViewRef.reattach();

        this.childViewRef.detectChanges();

        this.childViewRef.detach();

    } catch (ex) {

        // ignored

    }

  }


  protected addSubscriptions(subs: Subscription) {

    this.subscriptions.push(subs);

  }


  protected unSubscribeSubscriptions() {

    this.subscriptions.forEach(item => item.unsubscribe());

    this.subscriptions = [];

  }

}

除应用程序组件外,所有组件都继承此基本组件,因此第二组件的代码如下所示。


@Component({

  selector: 'second-comp',

  templateUrl: './SecondComponent.component.html',

  styleUrls: ['./SecondComponent.component.css'],

  changeDetection: ChangeDetectionStrategy.OnPush

})

export class SecondComponent extends BaseComponent implements OnInit, AfterViewInit{

   constructor(private ref:ChangeDetectorRef){

     super(ref);  

   }


   ngAfterViewInit(): void {

     this.updateUi();

     this.publishHeight()

   }


   ngOnInit() {

    this.updateUi();

    this.publishHeight()

   }

}

有什么不对吗,我得到了这种意想不到的行为。


侃侃无极
浏览 167回答 3
3回答

婷婷同学_

计算在 ngOn 初始化内的第二次合成中设置超时() 中的高度&nbsp;setTimeout(()&nbsp;=>&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//calculateHeight()&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;200);

慕田峪7331174

感觉你做错了。您可以在第二复合构造函数中注入@Self,它将为您提供自身的元素Ref(第二复合)。constructor( @Self() private element: ElementRef ) {}它可能不起作用,但不会受到第一次竞争的影响ngOnInit() {&nbsp; &nbsp; this.element.nativeElement.offsetHeight //the height for whatever you need it for}

HUH函数

您应该计算组件视图完全呈现时的高度。这意味着计算&nbsp;ng 内部的高度后查看初始化()&nbsp;钩子。请参阅&nbsp;https://angular.io/api/core/AfterViewInit
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript