Angular 2+ 中 setTimeout 的替代方案

Nim*_*oel 6 javascript settimeout typescript ngrx angular

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

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

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

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

下面是 HTML div。

<div  #datalist id="mydata" *ngIf="clientSearchResults$ | async  as searchResults" 
class = 'result'>
  <p> hellooo</p>
</div>
Run Code Online (Sandbox Code Playgroud)

将数据分派到存储后,我在我的 div 中获取滚动。但我不想使用setTimeout. 它不必要地等待 300 毫秒。有没有其他方法可以做到这一点?我只想滚动到我的div,当我的数据被发送或 ngif 条件得到满足时。

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

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

amu*_*amu -2

假设clientSearchResults$在调度时会发出一个新值SetClientSearchResultsAction,您可以在组件中订阅clientSearchResults$并从那里启动滚动。

ngOnInit() {
  clientSearchResults$
  .subscribe(() => {
    this.myScrollContainer.nativeElement.scrollIntoView({ behavior:'smooth', block: 'start'});
  });
}
Run Code Online (Sandbox Code Playgroud)