Javascript 使条件元素自动滚动到视图中的最佳方法

Javascript 使条件元素自动滚动到视图中的最佳方法,javascript,angular,Javascript,Angular,我有一个元素有条件地插入了*ngIf条件。当它被插入时,我想将其滚动到视图中。下面的技术很有效,但看起来很笨拙,我想改进一下 当组件状态属性modeNewEntry变为true时,文本输入框将插入页面底部。如果没有scrollIntoView()调用,它通常是不可见的 有没有比document.getElementById(..)表达式更好的方法来访问HTMLElement 另外,我正在使用的IDE WebStorm认为文档引用是未定义的,尽管它确实有效。这是错误还是原因?在包装div中添加

我有一个元素有条件地插入了
*ngIf
条件。当它被插入时,我想将其滚动到视图中。下面的技术很有效,但看起来很笨拙,我想改进一下


当组件状态属性
modeNewEntry
变为
true
时,文本输入框将插入页面底部。如果没有
scrollIntoView()
调用,它通常是不可见的

有没有比
document.getElementById(..)
表达式更好的方法来访问
HTMLElement


另外,我正在使用的IDE WebStorm认为
文档
引用是未定义的,尽管它确实有效。这是错误还是原因?

在包装
div
中添加组件:

<div #textCreate>
  <app-text-create id="textcreate" *ngIf="modeNewEntry">
  </app-text-create>
</div>
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  modeNewEntry = false;
  @ViewChild('textCreate', { static: false }) textCreateComponent: ElementRef;

  showComponent() {
    this.modeNewEntry = true;
    this.textCreateComponent.nativeElement.scrollIntoView();
  }
}


这里有一个您是否尝试过使用引用的例子?我曾考虑过使用ViewChild装饰器,但我忘记了它包含的nativeElement属性。而且我不再需要id属性了。