【问题标题】:div that scroll at the bottom in Angular2在Angular2底部滚动的div
【发布时间】:2019-02-23 19:31:53
【问题描述】:

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

情况是这样的:

滚动的div有这个css:

.element-list{
  width:100%;
  max-height: 180px;
  overflow-y: auto;
}

topBar 的 height20px,主包装器是 200px

在滚动的div里面,在html里面,有这样的东西(对你没用,只是为了让你更好理解):

<div class="something" *ngFor="let data of myData">
  <div>{{data.id}}</data>
</div>

这很好用,每当我在 myData 中添加一些东西时,都会反映到 ngFor 中,所以我看到越来越多的 &lt;div&gt;{{data.id}}&lt;/data&gt;

我想要实现的是在有触发overflow-y: auto;的元素时在底部自动滚动。

我的意思是:因为我的元素很少(比如说,十个元素),所以滚动条是隐藏的。但是当元素超过十个时,滚动条出现了,但并没有到底部。

像这样:

如您所见,还有更多元素。我想要的是 div 会自动滚动到底部。因此,即使添加了某些内容,它也将始终是这样的:

有没有办法在 Angular 中或通过 scss/css 来实现?

【问题讨论】:

  • 你当然可以挂钩数据添加事件,然后使用 element.scrollIntoView()
  • 是的,synoon 说,如果 .length 大于 3 或者只是执行 document.getElementByClass('element-list').scrollIntoView(false); 或使用 elementref 的东西,我会说只是触发一个方法,无论如何......

标签: javascript css angular sass


【解决方案1】:

使用 ngAfterViewChecked

在视图完成后调用 scrollBottom()

working sample - 点击添加按钮 UI 进行实验

html

<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;
  }

【讨论】:

  • 如果您觉得它有帮助,请确保您接受并支持答案
  • 当我尝试“说”ElementRef 是any 类型时,它给了我一个不可能的错误,所以我删除了那个&lt;any&gt; 并且它不起作用
  • @JacopoSciampi 你检查过我提供的样本吗?
  • 当然,但它说“元素引用不是通用的”
  • 有没有使用不同版本的angular和angular材质包?
猜你喜欢
  • 2012-07-13
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多