【问题标题】:Scroll Top not working correctly in angular2滚动顶部在 angular2 中无法正常工作
【发布时间】:2019-01-27 15:43:48
【问题描述】:

我创建了一个动态填充行的表。我有一个添加按钮,我也可以在其中添加行。这里我想在添加一行后在底部的表格中显示新添加的行,所以我使用下面的代码是component.ts。

this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;

但上面的代码似乎不能正常工作。 问题是当我添加新行时,滚动并没有完全到 div 标签的底部,因此看不到新行。

下面是我的 html 代码,我在 div 标签内使用了一个表格,如下所示。

<div style="height:200px;overflow-y:auto">
    <table class="table table-bordered table-hover">
        <thead>
        <tr class="d-flex">
            <th class="col-3">Q.No</th>
            <th class="col-4">Record Answer</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let answer of answerPaper; let i = index" class="d-flex">
            <td class="col-3">answer.no</td>
            <td class="col-4">answer.name</td>
        </tr>
        </tbody>
    </table>
</div>
<button (click)="addrow()">Add Row</button>

下面是component.ts

public addRow(){
    this.answerPaper.push({});
}

我也在发布滚动条的图像。

当我添加一个新行时,滚动条没有完全移动到 div 的底部,因此没有完全看到新添加的行

我是不是哪里出错了?

【问题讨论】:

  • 使用这个this.document.body.scrollTop = 0;

标签: javascript html angular


【解决方案1】:

一旦角度元素准备好,将滚动条调用到顶部或底部

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

  ngAfterViewChecked() {
    this.scrollBottom()
  }

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

SLACKBLITZ

【讨论】:

  • 感谢您的回复。这就是我要找的。​​span>
  • 它对我有用,在我的情况下,我只需要滚动顶部,并且只能使用本机元素以这种方式工作。
  • 我的代码可能有什么问题,该方法执行没有问题,但屏幕没有移动。
【解决方案2】:

就我而言,我想在添加新评论时向下滚动评论列表。
但逻辑是一样的。
我定义了一个变量scrollDown: number;,然后像这样恢复评论列表:

@ViewChild('commentList') commentList: ElementRef;

然后,当添加评论时:

this.scrollDown = this.commentList.nativeElement.scrollHeight;

最后,在模板中:

<div #commentList class="document-comments-list" [scrollTop]="scrollDown">

【讨论】:

  • 感谢您的回复。这就是我要找的。​​span>
【解决方案3】:

[临时快速修复] 添加计时器对我有用,

ngAfterViewChecked() {
  setTimeout(this.scrollBottom(), 500)
}

【讨论】:

  • 谢谢!!这个解决方案对我有用。
猜你喜欢
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
  • 2011-04-26
相关资源
最近更新 更多