1. 程式人生 > 其它 >angular拖拽元素

angular拖拽元素

由於官網無法登陸所以參考csdn angular拖拽案例 滾動條屬性設定

需求:把ng-zorro表格頭部做成可拖拽的形式

思路:拖拽表格最簡單的實現就是把表格的元素設計成陣列渲染,通過改變陣列元素來渲染表頭,上程式碼

APP.component.html

  <nz-table #basicTable [nzData]="listOfData" [nzPageSize]="2" [nzPageSizeOptions]="[1,2,3,4,5]"
    [nzShowPagination]="true" nzShowSizeChanger [nzScroll]="{y:'100px'}"
> <thead> <tr cdkDropListOrientation="horizontal" class="example-list" cdkDropList (cdkDropListDropped)="droptest($event)"> <th *ngFor="let i of tharr;" class="example-box" nzAlign="center" cdkDrag>{{i}} </th> </tr> </thead> <tbody> <tr *ngFor="
let data of basicTable.data"> <td *ngFor="let i of tharr let index=index" [nzAlign]="thFont(index)">{{ thHear(data,i) }} </td> </tr> </tbody> </nz-table>

less

.example-list {
    width: 100%;
    min-height: 60px;
    flex-direction: row;
    background
: white; border-radius: 4px; overflow: hidden; } //拖拽目標樣式 .cdk-drag-preview { position: relative; color: rgba(0, 0, 0, 0.85); font-weight: 500; background: #fafafa; border-bottom: 1px solid #f0f0f0; transition: background 0.3s ease; padding: 16px 16px; } //拖拽時原目標元素樣式 .cdk-drag-placeholder { opacity: 0; } //放入新位置動畫效果 .cdk-drag-animating { transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); } //拖拽移動效果 .example-list.cdk-drop-list-dragging .example-box:not(.cdk-drag-placeholder) { transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); } //table //懸浮樣式修改 ::ng-deep .ant-table-tbody > tr.ant-table-row:hover > td, .ant-table-tbody > tr > td.ant-table-cell-row-hover.ant-table-tbody>tr:hover { background:slategrey; } //偶數行變色 ::ng-deep table tbody> tr:nth-child(even){ background:greenyellow; } //奇數行變色 ::ng-deep table tbody> tr:nth-child(odd){ background:bisque; } //去頭部空格 ::ng-deep.nz-table-hide-scrollbar{ overflow: visible !important; } //去滾動條 ::ng-deep::-webkit-scrollbar{ display: none; }

ts

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {

  tharr = ['name', 'age', 'address']
  thFontStyle: any[] = ['left', 'center', 'right']
  listOfData: any = [];
  thHear(value: any, attribute: any) {
    return value[attribute]
  }
  thFont(value: any): "left" | "right" | "center" | null {
    return this.thFontStyle[value]
  }
  droptest(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.tharr, event.previousIndex, event.currentIndex);
  }
  ngOnInit() {
    for (let i = 0; i < 20; i++) {
      this.listOfData.push({
        key: i,
        name: `John Brown${i}`,
        age: i,
        address: `New York No. ${i} Lake Park`
      })
    }
  }
}