Angular 4滚动两个单独的元素 [英] Angular 4 scroll two seperate elements togther

查看:120
本文介绍了Angular 4滚动两个单独的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个演示此处

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

I'm capturing the scrollLeft of one element as it's scrolled.

是否可以用scrollLeft号更新第二个div,以便两个div一起向左和向右滚动?

Is it possible to update the second div with the scrollLeft number so both div scroll left and right together?

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

The elements have to be separate but I need them to scroll together.

或者在Angular中有一种更简单的方法来做到这一点.

Or is there a simpler way to do this in Angular.

我在jQuery的Angular之外进行了此工作,但我不想在Angular中使用jQuery.

I had this working outside of Angular with jQuery but I don't want to use jQuery in Angular.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  isNavbarCollapsed = true;

  private scrollLeft: number
  //private scrolLTwo: HTMLElement = 

  onScroll(event: Event) {
    this.scrollLeft = (event.target as HTMLElement).scrollLeft;
    //console.log(this.scrollLeft);
    this.updateScroll();
  }

  updateScroll(){
    //Update second scrolling element
  }
}

推荐答案

您只需获得对第二个<div>的引用,并将其向左滚动到相同的数量即可:

You can just get a reference to the second <div> and set it's scroll left to the same amount:

<div class="container" (scroll)="scrollTwo.scrollLeft = scrollOne.scrollLeft" #scrollOne>
    ...
</div>
<div class="container" #scrollTwo>
    ...
</div>

如果要在组件中使用更复杂的逻辑来管理滚动量应为多少,则可以通过@ViewChild来获得对两个DOM节点的引用:

If you want to have more complicated logic in your component to manage what the scroll amount should be, you can just get the reference to the two DOM nodes via @ViewChild:

<div class="container" (scroll)="updateScroll()" #scrollOne>
    ...
</div>
<div class="container" #scrollTwo>
    ...
</div>

@Component(...)
export class AppComponent  {
  @ViewChild('scrollOne') scrollOne: ElementRef;
  @ViewChild('scrollTwo') scrollTwo: ElementRef;

  updateScroll(){
    const scrollOne = this.scrollOne.nativeElement as HTMLElement;
    const scrollTwo = this.scrollTwo.nativeElement as HTMLElement;

    // do logic and set
    scrollTwo.scrollLeft = scrollOne.scrollLeft;
  }
}

您不必通过@ViewChild获取引用.您宁愿只是将它们传递给称为:

You don't have to get the references via @ViewChild. You could rather just pass them into the method that is called:

<div class="container" (scroll)="updateScroll(scrollOne, scrollTwo)" #scrollOne>
    ...
</div>
<div class="container" #scrollTwo>
    ...
</div>

@Component(...)
export class AppComponent  {
  updateScroll(scrollOne: HTMLElement, scrollTwo: HTMLElement){
    // do logic and set
    scrollTwo.scrollLeft = scrollOne.scrollLeft;
  }
}

这篇关于Angular 4滚动两个单独的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆