Angular 角度4将两个单独的元素滚动到一起

Angular 角度4将两个单独的元素滚动到一起,angular,Angular,我有一个演示 我正在捕获一个元素滚动时的scrollLeft 是否可以使用scrollLeft编号更新第二个div,以便两个div同时向左和向右滚动 元素必须分开,但我需要它们一起滚动 或者,有没有一种更简单的方法来实现这一点 我在Angular之外使用jQuery实现了这一点,但我不想在Angular中使用jQuery 从'@angular/core'导入{Component}; @组成部分({ 选择器:“我的应用程序”, templateUrl:“./app.component.html”,

我有一个演示

我正在捕获一个元素滚动时的
scrollLeft

是否可以使用
scrollLeft
编号更新第二个div,以便两个div同时向左和向右滚动

元素必须分开,但我需要它们一起滚动

或者,有没有一种更简单的方法来实现这一点

我在Angular之外使用jQuery实现了这一点,但我不想在Angular中使用jQuery

从'@angular/core'导入{Component};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent{
名称='5';
IsNavBar=true;
私人卷轴左:号码
//私有滚动条2:HtmleElement=
onScroll(事件:事件){
this.scrollLeft=(event.target作为HTMLElement).scrollLeft;
//console.log(this.scrollLeft);
this.updateScroll();
}
updateScroll(){
//更新第二个滚动元素
}
}

您只需获取第二个
的参考,并将其向左滚动设置为相同的数量:


...
...
如果您希望在组件中有更复杂的逻辑来管理滚动量,您可以通过
@ViewChild
获取对两个DOM节点的引用:


...
...
@组件(…)
导出类AppComponent{
@ViewChild('scrollOne')scrollOne:ElementRef;
@ViewChild('scrollTwo')scrollTwo:ElementRef;
updateScroll(){
const scrollOne=this.scrollOne.nativeElement作为HTMLElement;
const scrollTwo=this.scrollTwo.nativeElement作为HTMLElement;
//做逻辑和设置
scrollTwo.scrollLeft=scrollOne.scrollLeft;
}
}
您不必通过
@ViewChild
获取引用。您可以直接将它们传递到调用的方法中:


...
...
@组件(…)
导出类AppComponent{
updateScroll(scrollOne:HtmleElement,scrollTwo:HtmleElement){
//做逻辑和设置
scrollTwo.scrollLeft=scrollOne.scrollLeft;
}
}
角度CDK现在提供了。只需将
cdkScrollable
指令添加到所有需要保持同步的可滚动元素中,然后将此逻辑添加到组件中:

this.scrollDispatcher.scrolled().subscribe((可滚动:CdkScrollable)=>{
如果(可滚动的类型=='undefined'){
返回true;
}
const left=scrollable.measureScrollOffset('left');
Array.from(this.scrollDispatcher.scrollContainers.keys())
.filter(otherScrollable=>otherScrollable&&otherScrollable!==scrollable)
.forEach(其他可滚动=>{
if(otherScrollable.measureScrollOffset('left')!==left){
otherScrollable.scrollTo({left});
}
});
});
当组件被销毁时,不要忘记取消订阅此订阅。并在构造函数中注入
ScrollDispatcher
服务:

公共构造函数(私有scrollDispatcher:scrollDispatcher){}

该问题的可能重复项有jQuery答案。我想尝试使用Angular而不是jQuery来实现这一点。我有一个jQuery解决方案不起作用。谢谢。我甚至不需要使用CdkScrollable指令,因为我使用的是cdk虚拟滚动视口,它只是开箱即用。我在订阅中未定义滚动。