我将数据发送到ngrx商店。之后,我想滚动到一个特定的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>在将数据发送到存储后,我将在div上获得滚动。但我不想使用setTimeout。这是不必要地等待300毫秒。有什么替代的方法来做吗?我只想滚动到我的div,当我的数据被发送或ngif条件被满足时。
下面是从Store获取值的组件的构造函数。
constructor(private store: Store<AppState>,
private formBuilder: FormBuilder, private _clientService: ClientService) {
this.clientSearchResults$ = this.store.select('searchResults');
}发布于 2018-04-03 09:30:53
您可以使用Lifecycle,在角初始化组件的视图和子视图/指令所在的视图之后,AfterViewInit响应。
class MyComponent implements AfterViewInit {
ngAfterViewInit() {
// ...
}
}发布于 2022-08-15 10:14:56
使用RXJS有多种方法
选项1 -带asapScheduler
asapScheduler.schedule(() => { // Your Code });选项2 -带interval
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
interval(0).pipe(take(1),
).subscribe(value => { // Your Code });选项3 -带Promise
Promise.resolve().then(() => { // Your Code });最优的方法是使用选项1,因为它是为了避免setTimeout(deferredTask, 0)而制作的。
来自RxJS文档中的asapScheduler
asap调度程序将尽力减少当前执行代码结束到计划任务开始之间的时间。这使它成为执行所谓“推迟”的最佳人选。传统上,这是通过调用setTimeout(deferredTask,0)来实现的,但是这种技术涉及一些(尽管是最小的)不必要的延迟。
发布于 2018-04-03 09:30:38
假设clientSearchResults$在分派SetClientSearchResultsAction时会发出一个新值,您可以在组件中订阅clientSearchResults$并从那里开始滚动。
ngOnInit() {
clientSearchResults$
.subscribe(() => {
this.myScrollContainer.nativeElement.scrollIntoView({ behavior:'smooth', block: 'start'});
});
}https://stackoverflow.com/questions/49626354
复制相似问题