In the era of digitalization, many users have migrated from Excel spreadsheet to modern web applications but they are still expecting to find the same features and functions that they have used for years with their old friend Excel. The bad news is that a such expectation, which is out of discussion, could be a nightmare for a frontend developer.
One of those very asked features is a data table that offers the possibility to inline edit multiple cells without a click on an edit-icon then open a dialog where the user have to enter the new value for the cells. Sometimes the developers choose to add a third party library that offer this function to the application, because they don’t know how much time is needed to implement it by their own.
So, if you have a such requirement and you think you need a third party library, may be you will change your mind after reading this post. All what we need here is Angular and Angular Material (our app is using Angular 7). So, let’s get started.
We are going to scaffold our app using the Angular CLI. First, we need to install it:
npm install -g @angular/cli
Then create our app:
ng new mat-edit-table
Alright, time for the good stuff. We have to follow the next steps:
- Install angular material:
npm install @angular/material
npm install @angular/cdk
npm install hammerjs
- Import angular theme. Add this line to src/style.scss:
- Update AppModule app.module.ts:
- Replace the content of app.component.html with the following:
- Replace the content of app.component.ts with the following:
This is the result after running “ng serve” and calling localhost:4200 with the browser:
- Now, we need to add the mousedown and mouseup events listeners to the editable cells. We want to edit just the cells from the columns name, weigh and symbol.
- As you have seen we’ve used 2 new CSS classes ‘selected’ and ‘unselected’ to show or hide a blue border around the selected cells depending on their states which are saved in the two dimensions array selectedCellsState.
Add keyup event listener. Update app.component.html by adding (keyup)=”onKeyUp($event)” event listener to the <table> tag and update app.component.ts:
- By default the browser will add a blue background to the selected area. For a better UX, we will remove this default behavior after selecting cells:
The complete code is available on github here.
One last thing
We have 2 different types of columns in our 1table: string and number. So, it will be awkward if the user select cells from different columns and enter the same new value fro them. For this reason, the onMouseDown and onMouseUp methods have a third parameter cellsType. If the user starts to enter a value for cells with different types, he will receive an alert in a snackBar:
That’s it for today. In the next article you will see how to export this table as an Angular Library to be able to use it in different angular projects by adding it to package.json just like others npm dependencies.