Inline Editable Table Using Reactive Forms in Angular

Vaibhav Phutane
2 min readOct 30, 2018

Table Features
1. Add row
2. Edit row
3. Delete row
4. Validate column / row / entire table
5. Dark Mode
6. Updating touched / dirty rows only
7. Scroll-able columns

Playing with a table is always fun in Angular. Many times users want to add, delete or interactively update a record of a table. To achieve this we can take leverage of Angular dynamic form controls.

Demo

Github Repository

Implementation

We will treat each row as single FormGroup and the whole table as parent FormGroup structure will look like.

Table ---> Parent FormGroup
-Row 1
-Row 2 --> child FormGroups

Steps:
Install all required dependencies

ng add @angular/material -save
npm install bootstrap --save
npm install jquery --save

Create new user component

ng generate component user-table

Import ReactiveFormsModule in app.module.ts from @angular/forms
also, import all required angular material modules

app.module.ts

Create userTable of type FormGroup having tableRows as formArray this users table array will consist formGroups with controls like name, email, etc

Add row

On click of add button new row would be added at the end of the table. It adds new FormGroup to FormArray

Delete row

On the click of the trash icon, the user will able to delete particular user data from the table. It removes particular FormGroup from FormArray

The following code is pretty self-explanatory.

user-table.component.ts

user-table.component.ts

Now bind this FormGroups and FormControls in user-table.component.html

user-table.component.ts

Validations

We can always add validation to each FormControl. Also, we can add our custom validations.

It works as follows

FormControls —validate→ TableRows — validate → Table

Let’s add required, maxLength, email validations to respective controls

user-table.component.ts

user-table.component.ts

When multiple rows were added to the table then userTable.valid is true only when each and every row in the table is valid.
If you observe it saves only updated/touched rows.

Drag-able Column

Create a directive which will listen to mousedown and DragEvent

dragable-column.directive.ts

Add some scss change in user-table.component.scss

Now use this drag-able directive on table heading <th> .
user-table.component.html

Happy Coding….Cheers…!

--

--