Angular 更改零部件的可见性并滚动到不在角度方向工作的零部件

Angular 更改零部件的可见性并滚动到不在角度方向工作的零部件,angular,Angular,我有一个父组件,其中包含多个组件: <div class="mx-sm-auto mb-5 px-0 container"> <app-set-vehicle-details id="step1" #step1 (step1Finished)="enableStep2()"></app-set-vehicle-details> <app-product-selection id="step2" *ngIf="step2Enabled">&

我有一个父组件,其中包含多个组件:

<div  class="mx-sm-auto mb-5 px-0 container">
  <app-set-vehicle-details id="step1" #step1 (step1Finished)="enableStep2()"></app-set-vehicle-details>
  <app-product-selection id="step2" *ngIf="step2Enabled"></app-product-selection>
  <app-product-additional id="step3" *ngIf="step3Enabled"></app-product-additional>
</div>
所以
step2
组件可见,但滚动到它时它不工作。 我假设发生这种情况是因为在调用
scrollToElement
之前,第二个组件的可见性没有设置为true,因为一旦组件可见,它就会工作

我如何通过这种行为来实现这一目标


谢谢

您可以通过订阅
QueryList.changes
事件,使用
ViewChildren
监视子组件的存在

首先,在子组件上设置模板引用变量:

<app-product-selection #step2 *ngIf="step2Enabled"></app-product-selection>
请参阅演示。

我的解决方案是:

enableStep2() {
   this.step2Enabled = true;
   setTimeout(() => {
     this.scrollToElement('step2');
   });
}

这将等待步骤2可见。太完美了

您正在滚动到一些尚不存在的内容。它将只存在于下一次渲染中。是的,这就是我怀疑的原因。我怎样才能做到这一点?(这确实是我真正的问题…)最简单的方法是切换
显示:无
css样式,而不是
*ngIf
隐藏这些元素。两者都不工作…我解决了它,增加了50毫秒的延迟。。。。
@ViewChildren("step2", { read: ElementRef }) step2List: QueryList<ElementRef>;

ngAfterViewInit() {
  this.step2List.changes.subscribe(() => {
    if (this.step2List.length > 0) {
      (this.step2List.first.nativeElement as HTMLElement).scrollIntoView();
    }
  });
}
enableStep2() {
   this.step2Enabled = true;
   setTimeout(() => {
     this.scrollToElement('step2');
   });
}