【问题标题】:Scroll to latest added element in *ngFor loop in Angular2滚动到 Angular2 的 *ngFor 循环中最新添加的元素
【发布时间】:2017-07-17 20:20:42
【问题描述】:

我有 ngFor 循环渲染 HTML div。这个循环后面的列表是动态的,这意味着页面显示一个按钮,允许从列表中添加或删除元素。 我想要实现的是,当用户单击以在列表中添加新元素时,将浏览器视图滚动到添加的最新元素。

scrollToView(true) 不起作用,因为当我传入添加新元素的 javascript 函数时,*ngFor 循环尚未呈现该元素。

HTML 页面

<div class="container"><div class="row">

<div *ngIf="selection.length <= 0" class="align-sm-right">
  <button id="add-selection-default" class="btn app-btn-primary anim-bg"
          (click)="add()">
    <i class="material-icons">add</i><span>Add</span></button>
</div>

<div *ngFor="let sel of selection; let index = index; let last = last">

  <div id="{{'id' + index}}" class="form-sub-section">
  </div>

</div>

添加文档的方法调用

  add() {
this.selection.push({});

// code to scroll to newly added element

}

是否有一些解决方案使用 onCreate 或其他方法来检测何时添加和呈现元素,然后滚动到该特定元素?

谢谢, 问候,

【问题讨论】:

  • 相关代码在哪里?

标签: html angular typescript


【解决方案1】:

我个人是这样使用ng2-page-scroll

constructor(
  private pageScroll: PageScrollService,
) {
  PageScrollConfig.defaultDuration = 500;
  PageScrollConfig.defaultEasingLogic = {
    ease: (t: number, b: number, c: number, d: number): number => {
      // ease-in-out easing function
      if (t === 0) { return b; }
      if (t === d) { return b + c; }
      if ((t /= d / 2) < 1) { return c / 2 * Math.pow(2, 10 * (t - 1)) + b; }
      return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
    }
  };
}

当你想去页面中的某个位置时,使用

this.pageScroll.start(PageScrollInstance.simpleInstance(document, '#yourLocationId'));

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2017-07-11
    • 2017-07-26
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2016-11-05
    • 2017-02-09
    • 2017-08-06
    相关资源
    最近更新 更多