Javascript 以角度2在底部滚动的div

Javascript 以角度2在底部滚动的div,javascript,css,angular,sass,Javascript,Css,Angular,Sass,很抱歉标题不好,我真的不知道如何用几句话写出有意义的东西 情况是这样的: 滚动的div具有以下css: .element-list{ width:100%; max-height: 180px; overflow-y: auto; } 顶栏的高度为20px,主包装为200px 在滚动的div中,在html中,有这样的内容(这对您来说是无用的,但只是为了让您更好地理解): {{data.id} 这很好,每当我在myData中添加一些内容时,就会反映到ngFor中,因此我看到越来

很抱歉标题不好,我真的不知道如何用几句话写出有意义的东西

情况是这样的:

滚动的div具有以下css:

.element-list{
  width:100%;
  max-height: 180px;
  overflow-y: auto;
}
顶栏的
高度为
20px
,主包装为
200px

在滚动的div中,在html中,有这样的内容(这对您来说是无用的,但只是为了让您更好地理解):


{{data.id}
这很好,每当我在
myData
中添加一些内容时,就会反映到ngFor中,因此我看到越来越多的
{{data.id}

我试图实现的是,每当有触发
overflow-y:auto的元素时,在底部自动滚动

我的意思是:因为我只有很少的元素(比如说,十个元素),所以滚动条是隐藏的。但是当元素超过10个时,滚动条会出现,但不会进入底部

像这样:

正如你所看到的,还有更多的元素。我想要的是,div将自动滚动到底部。因此,当添加任何内容时,它将始终是这样的:

有没有办法用Angular或通过scss/css进行此操作?

在查看完成后使用ngAfterViewChecked调用scrollBottom()

-单击添加按钮UI以进行实验

html


{{i.name}

添加 滚动到顶部 滚动到底部
组成部分

@ViewChild('scroll', { read: ElementRef }) public scroll: ElementRef<any>;

  ngAfterViewChecked() {
    this.scrollBottom()
  }

  public scrollBottom() {
    console.log(this.scroll.nativeElement.scrollTop);
    this.scroll.nativeElement.scrollTop = this.scroll.nativeElement.scrollHeight;

  }

  public scrollToTop() {
    this.scroll.nativeElement.scrollTop = 0;
  }
@ViewChild('scroll',{read:ElementRef})公共滚动:ElementRef;
ngAfterViewChecked(){
this.scrollbooth()
}
公共滚动底部(){
console.log(this.scroll.nativeElement.scrollTop);
this.scroll.nativeElement.scrollTop=this.scroll.nativeElement.scrollHeight;
}
公共滚动totop(){
this.scroll.nativeElement.scrollTop=0;
}

您当然可以挂接到添加数据的事件中,然后使用element.scrollIntoView(),就像synoon说的那样,如果.length大于3,或者只是执行
document.getElementByClass('element-list')。scrollIntoView(false)之类的操作,我会说只需启动一个方法即可
或使用elementref,无论什么……如果你觉得答案有用,请确保你接受并投票。当我试图“说”elementref属于
any
类型时,它会给我一个不可能是任何类型的错误,因此我删除了
,但它不是working@JacopoSciampi你检查过我提供的样品了吗?当然,但上面写着“元素参考不是通用的”您是否使用了不同版本的角度和角度材料包?
<div style="height:200px; overflow-y:auto;" #scroll>
    <div *ngFor="let i of list">
        {{i.name}}
        <br>
    </div>
</div>


<button (click)="Add()">Add</button>

<button (click)="scrollToTop()">Scroll to top</button>
<button (click)="scrollBottom()">Scroll to bottom</button>
@ViewChild('scroll', { read: ElementRef }) public scroll: ElementRef<any>;

  ngAfterViewChecked() {
    this.scrollBottom()
  }

  public scrollBottom() {
    console.log(this.scroll.nativeElement.scrollTop);
    this.scroll.nativeElement.scrollTop = this.scroll.nativeElement.scrollHeight;

  }

  public scrollToTop() {
    this.scroll.nativeElement.scrollTop = 0;
  }