In this post, we are going to go through the complete example of how to implement Drag/Drop rows in Angular Material Table.
This is a step-by-step tutorial where you are going to learn how to add the Drag/Drop feature in the Angular Material Table. At the end of the document, you can find the YouTube video that contains the live working session on implementing drag-drop functionality on the angular material table.
Prerequisites
To begin with, you need to have a basic knowledge of Angular Framework, Angular Material with NodeJs, Angular CLI, and Visual Studio Code(VSC) installed in your system.
Creating New Project
In order to start with, create a new Angular project in the VSC editor by typing in the below command in the terminal.
ng new angular-drag-drop-table
After successfully creating the project open the project in VSC by clicking on File => Open Folder => angular-drag-drop-table(find the path wherever you have created the project). Now you can see the terminal updated with the project path.
Installing Angular Material
To begin with the table creation it is important to install Angular Material into the project by typing the below command in the terminal.
ng add @angular/material
Once the package is installed successfully import the modules that are necessary to proceed with the Drag/Drop feature.
Now, open the app.module.ts file and add MatTableModule provided by "@angular/material/table" and DragDropModuleprovided by "@angular/cdk/drag-drop"under the imports section.
app.module.ts
import { MatTableModule } from '@angular/material/table';
import { DragDropModule} from '@angular/cdk/drag-drop';
imports: [
...,
MatTableModule,
DragDropModule
]
export class AppModule { }
Set up app.component.ts
The next step is to configure the app.component.tswith the data that needs to be displayed on the table. Here I'm using the table shown in the example Angular Material Table.
Define columns and data as shown in the *ngFor example table. Now, define a method that will be performing Drag/Drop in our table rows as shown below.
Sometimes the table doesn't get updated on its own, In such cases call the renderRows method inside the drag method provided by MatTable as shown below.
this.table.renderRows();
Before adding the renderRows method define table as shown below.
@ViewChild(MatTable) table!: MatTable<any>;
Set up app.component.html
Now add the cdkDropList container into your table that wraps a set of draggable items along with the cdkDropListDropped event that emits when the user drops an item inside the container and binds the drag method with the event which was created in the previous step. Get the complete code by clicking app.component.html.
Comments
Post a Comment