1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Reorder columns in data table - Angular Material

Discussão em 'Angular' iniciado por developer8492, Agosto 7, 2025.

  1. I want to have the columns to be able to be reordered or moved around for a data table. The code implemented isn't working. Any time I try to reorder a column the column either gets stuck when trying to reorder or just doesn't work at all. I need assistance on what I am missing from the code. This code is what I've added to my existing code.

    html

    <th mat-header-cell *matHeaderCellDef
    cdkDropList
    cdkDropListLockAxis="x"
    cdkDropListOrientation="horizontal"
    (cdkDropListDropped)="dropListDropped($event, i)"
    cdkDrag
    (cdkDragStarted)="dragStarted($event, i)"
    [cdkDragData]="{name: column.field, columIndex: i}" >
    ..................
    ..................
    </th>


    ts

    columns: any[] = [
    { field: 'position' },
    { field: 'name' },
    { field: 'weight' },
    { field: 'symbol' }
    ];

    previousIndex: number;

    setDisplayedColumns() {
    this.columns.forEach(( colunm, index) => {
    colunm.index = index;
    this.displayedColumns[index] = colunm.field;
    });
    }

    dragStarted(event: CdkDragStart, index: number ) {
    this.previousIndex = index;
    }

    dropListDropped(event: CdkDropList, index: number) {
    if (event) {
    moveItemInArray(this.columns, this.previousIndex, index);
    this.setDisplayedColumns();
    }
    }


    Demo - Stackblitz

    Continue reading...

Compartilhe esta Página