javascript - Angular 2+ 中 setTimeout 的替代方案

标签 javascript angular typescript settimeout ngrx

我正在将数据发送到 ngrx store .之后,我想滚动到特定的 div,它正在使用商店中的这些数据。

@ViewChild('datalist') private myScrollContainer: ElementRef; 

this.store.dispatch(new SetClientSearchResultsAction(filteredData));

setTimeout(() => {
this.myScrollContainer.nativeElement.scrollIntoView({ behavior:'smooth', block: 'start'});
 }, 300);

下面是 HTML div。

<div  #datalist id="mydata" *ngIf="clientSearchResults$ | async  as searchResults" 
class = 'result'>
  <p> hellooo</p>
</div>

在将数据分派(dispatch)到存储后,我在我的 div 中获得了滚动条。但我不想使用 setTimeout。它不必要地等待 300 毫秒。是否有任何替代方法来做到这一点?我只想滚动到我的 div,当我的数据被分派(dispatch)或 ngif 条件得到满足时。

下面是我从 Store 获取值的组件的构造函数。

constructor(private store: Store<AppState>,
    private formBuilder: FormBuilder, private _clientService: ClientService) {
    this.clientSearchResults$ = this.store.select('searchResults');
  }

最佳答案

可以使用Lifecycle hook,AfterViewInit在Angular初始化组件的 View 和 subview /指令所在的 View 后进行响应。

class MyComponent implements AfterViewInit {
  ngAfterViewInit() {
    // ...
  }
}

关于javascript - Angular 2+ 中 setTimeout 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49626354/

相关文章:

javascript - 网站无法在 Chrome 中使用箭头键滚动

angular - 将 Angular 路由的路径提取到单独的文件中

TypeScript 按任意类型过滤元组类型

javascript - RxJs 管道和可出租运算符 `map` : 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'

javascript - react ( native ): Pass a prop with the value obtained from an async function

javascript - 停止我的网站在智能手机上的自动旋转

javascript - jQuery 对齐网格问题

angular - 仅列出 Azure Blob 存储中 100 个 Blob 中的 10 个 Blob

angular - 如何通过 Angular 4 中的共享模块正确导入 Angular Material 模块?

Angular 2 : two way binding inside parent/child component