angular ngzorro 表格用自定义指令实现自由缩放列宽

版本

“@angular/core”: “~10.0.3”
“ng-zorro-antd”: “^10.2.2”

实现思路

可通过自定义指令,设置一个元素定位在th上,拖动该元素,存储鼠标按下时刻的列宽和鼠标事件的screenX值记为oldScreenX,鼠标move事件是newScreenX,得到移动的距离newScreenX - oldScreenX

dynamic-column-width.directive.ts

import { Directive, ElementRef, OnInit } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';

@Directive({
  selector: '[appDynamicColumnWidth]'
})
export class DynamicColumnWidthDirective implements OnInit {
  private mousedown$: Observable<any>;
  private mousemove$: Observable<any>;
  private mouseup$: Observable<any>;
  private down = false; // 是否按下
  private lastX: number;
  private lastWidth: number;

  constructor(private el: ElementRef) { }

  ngOnInit(): void {
    // 创建拖动定位按钮
    const span = document.createElement('span');
    span.className = 'resize-bar';
    this.el.nativeElement.style.position = 'relative'
    this.el.nativeElement.appendChild(span);

    this.mousedown$ = fromEvent(span, 'mousedown');
    this.mousemove$ = fromEvent(document, 'mousemove');
    this.mouseup$ = fromEvent(document, 'mouseup');

    this.mousedown$
      .subscribe((event: MouseEvent) => {
        this.down = true;
        this.lastX = event.screenX;
        this.lastWidth = this.el.nativeElement.offsetWidth;
      })


    this.mousemove$
      .subscribe(event => {
        if (this.down) {
          this.el.nativeElement.style.width = event.screenX - this.lastX + this.lastWidth + 'px';

        }
      })

    this.mouseup$
      .subscribe(event => {
        this.down = false;
      })
  }
}

应用在html上

<nz-table #nzTable id="table" [nzData]="listOfData" >
  <thead>
    <tr>
      <th nzWidth="160px" appDynamicColumnWidth data-index="0">Nameth>
      <th nzWidth="160px" appDynamicColumnWidth>Ageth>
      <th appDynamicColumnWidth>Addressth>
      <th appDynamicColumnWidth>Actionth>
    tr>
  thead>
  <tbody>
    <tr *ngFor="let data of nzTable.data">
      <td>{{data.name}}td>
      <td>{{data.age}}td>
      <td>{{data.address}}td>
      <td><a>Deletea>td>
    tr>
  tbody>
nz-table>

style.less

.resize-bar {
  width: 20px;
  height: 55px;
  background-color: rgba(255,0,0,0.5);
  position: absolute;
  right: -10px;
  top: 0;
  cursor: col-resize;
}

效果图

angular ngzorro 表格用自定义指令实现自由缩放列宽_第1张图片
红色的块鼠标划上就有可拖动箭头angular ngzorro 表格用自定义指令实现自由缩放列宽_第2张图片

后记

在公司项目里,设置th的宽度有坑。设置了nzWidth属性的列,怎么设置th.style.width都没有效果;需要去设置nztable默认渲染出来的元素的宽度,在th上增加data-index属性,获取table下的col,和th按照索引对应,设置col可实现自由伸缩列宽

你可能感兴趣的:(angular,javascript,前端,angular)