Angular 2 querySelector和addeventlistener

时间:2017-02-03 16:49:51

标签: angular dom typescript

onload = function() {
  var fcBody = document.querySelector(".fix-column > .tbody"),
      rcBody = document.querySelector(".rest-columns > .tbody"),
      rcHead = document.querySelector(".rest-columns > .thead");
  rcBody.addEventListener("scroll", function() {
      fcBody.scrollTop = this.scrollTop;
      rcHead.scrollLeft = this.scrollLeft;
  });
};

尝试以Angular 2方式计算上述代码。到目前为止,我已经提出使用ViewChild,然后尝试添加事件侦听器。我发现与HostListener有关,但它有点复杂

@ViewChild('fcBody') fcBody: any;
@ViewChild('rcBody') rcBody: any;
@ViewChild('rcHead') rcHead: any;

ngAfterViewInit(){
    this.rcBody.addEventListener("scroll", () => {
    this.fcBody.scrollTop = this.rcBody.scrollTop;
    this.rcHead.scrollLeft = this.rcBody.scrollLeft;
    });
}

如果可能的话,我宁愿避免使用指令,但如果它是最好的解决方案,那就这样吧。

1 个答案:

答案 0 :(得分:0)

按照Gunter的评论,我做了以下

<div #fcBody [scrollTop]="scrollTop" class="tbody">
<div #rcHead [scrollLeft]="scrollLeft" class="thead">
<div #rcBody (scroll)="scrollHandler($event)" class="tbody">

scrollHandler(event){
    this.scrollTop = event.srcElement.scrollTop;
    this.scrollLeft = event.srcElement.scrollLeft;
}

完美无缺。本质上,它使可滚动标题的标题滚动与可滚动表,并且冻结列垂直滚动可滚动表。如果这有助于你,请提出他的意见。