Skip to main content

Inline editable table-row using the edit button in Angular

In this tutorial, we will see an example of inline-editable rows of a table using mat-table.

To create an inline editable table row using the MatTable component in Angular, you will need to use Angular Material (@angular/material) for UI components, along with Angular's built-in data binding to manage the state of each row when the user clicks the Edit button.

Here's a step-by-step guide to implement this:

Step 1: Set Up Angular Material

First, you need to install Angular Material in your project. If you haven't already, run the following commands:

ng add @angular/material

During the installation, you will be prompted to select a theme and some other configuration options. You can choose the default options for now.

Step 2: Install Required Angular Material Modules

Next, you need to import the relevant Angular Material modules. Open your app.module.ts and import the necessary Material components:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MatTableModule } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    MatTableModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 3: Create the Table with Inline Editable Rows

Now, let's define the table with the edit functionality. We will use Angular Material's mat-table and two-way binding to make the table rows editable when the "Edit" button is clicked.

1. app.component.ts (Controller)

This TypeScript file will contain the logic to handle the inline editing.

import { Component } from '@angular/core';

interface Employee {
  id: number;
  name: string;
  position: string;
  salary: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  employees: Employee[] = [
    { id: 1, name: 'John Doe', position: 'Software Engineer', salary: 70000 },
    { id: 2, name: 'Jane Smith', position: 'Product Manager', salary: 85000 },
    { id: 3, name: 'Mark Johnson', position: 'Designer', salary: 65000 },
  ];

  editingRowIndex: number | null = null;
  originalEmployeeData: Employee | null = null;

  // Start editing a row
  startEditing(rowIndex: number) {
    this.editingRowIndex = rowIndex;
    this.originalEmployeeData = { ...this.employees[rowIndex] };
  }

  // Save the edited row
  saveEditing(rowIndex: number) {
    this.editingRowIndex = null;
    this.originalEmployeeData = null;
  }

  // Cancel editing a row
  cancelEditing(rowIndex: number) {
    if (this.originalEmployeeData) {
      this.employees[rowIndex] = { ...this.originalEmployeeData };
    }
    this.editingRowIndex = null;
    this.originalEmployeeData = null;
  }
}

2. app.component.html (Template)

In this HTML file, we will create the table using mat-table, and conditionally render the inputs for inline editing based on whether the row is being edited or not.

<div class="container">
  <h2>Employee Table</h2>
  <table mat-table [dataSource]="employees" class="mat-elevation-z8">
    
    <!-- ID Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef>#</th>
      <td mat-cell *matCellDef="let employee">{{ employee.id }}</td>
    </ng-container>
    
    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef>Name</th>
      <td mat-cell *matCellDef="let employee; let i = index">
        <ng-container *ngIf="editingRowIndex !== i">
          {{ employee.name }}
        </ng-container>
        <ng-container *ngIf="editingRowIndex === i">
          <input matInput [(ngModel)]="employee.name" />
        </ng-container>
      </td>
    </ng-container>

    <!-- Position Column -->
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef>Position</th>
      <td mat-cell *matCellDef="let employee; let i = index">
        <ng-container *ngIf="editingRowIndex !== i">
          {{ employee.position }}
        </ng-container>
        <ng-container *ngIf="editingRowIndex === i">
          <input matInput [(ngModel)]="employee.position" />
        </ng-container>
      </td>
    </ng-container>

    <!-- Salary Column -->
    <ng-container matColumnDef="salary">
      <th mat-header-cell *matHeaderCellDef>Salary</th>
      <td mat-cell *matCellDef="let employee; let i = index">
        <ng-container *ngIf="editingRowIndex !== i">
          {{ employee.salary | currency }}
        </ng-container>
        <ng-container *ngIf="editingRowIndex === i">
          <input matInput [(ngModel)]="employee.salary" type="number" />
        </ng-container>
      </td>
    </ng-container>

    <!-- Actions Column -->
    <ng-container matColumnDef="actions">
      <th mat-header-cell *matHeaderCellDef>Actions</th>
      <td mat-cell *matCellDef="let employee; let i = index">
        <ng-container *ngIf="editingRowIndex !== i">
          <button mat-raised-button (click)="startEditing(i)">Edit</button>
        </ng-container>
        <ng-container *ngIf="editingRowIndex === i">
          <button mat-raised-button color="primary" (click)="saveEditing(i)">Save</button>
          <button mat-raised-button color="warn" (click)="cancelEditing(i)">Cancel</button>
        </ng-container>
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>

3. app.component.css (Styles)

Here are some basic styles to make the table look nice:

.container {
  margin: 20px;
}

table {
  width: 100%;
}

button {
  margin-right: 5px;
}

input {
  width: 100%;
  padding: 5px;
}

Step 4: Define displayedColumns in app.component.ts

We need to define the columns that will be displayed in the table.

displayedColumns: string[] = ['id', 'name', 'position', 'salary', 'actions'];

Step 5: Run the Application

Run the application using:

ng serve

How It Works:

  • The table displays employee details with columns for ID, Name, Position, Salary, and Actions.
  • When the "Edit" button is clicked, it transforms the text into input fields for inline editing.
  • The user can modify the fields, and there are buttons to either Save or Cancel the changes.
  • If the Save button is clicked, the changes are applied, and the row stops being editable.
  • If the Cancel button is clicked, the changes are discarded, and the row returns to its original state.

Summary of Key Features:

  • MatTable: Angular Material's mat-table is used to create the table structure.
  • Two-way Data Binding (ngModel): For inline editing of each row.
  • Conditional Rendering: Each cell toggles between displaying static data and input fields based on the editing state of the row.
  • Angular Material Components: Buttons, input fields, and table elements are styled using Angular Material components (mat-buttonmat-input, etc.).

With this setup, you now have a table with editable rows and Angular Material's styling.

Comments

Popular posts from this blog

app-policy

PRIVACY POLICY Last updated April 19, 2023 This privacy notice for Team CoderzDuniya ( " Company ," " we ," " us ," or " our " ), describes how and why we might collect, store, use, and/or share ( " process " ) your information when you use our services ( " Services " ), such as when you: Download and use our mobile application ( Revenue Calculator) , or any other application of ours that links to this privacy notice Engage with us in other related ways, including any sales, marketing, or events Questions or concerns?  Reading this privacy notice will help you understand your privacy rights and choices. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at droidamar007@gmail.com . SUMMARY OF KEY POINTS This summary provides key points from our privacy notice, but you can find out more details about any of these t...

JavaFX WebView- Creating Browser Sample

Hi Friends, In this post, i am going to give an overview about JavaFX WebView . This is an embedded browser component which is based on WebKit . If allow you to use Css, JavaScript, HTML5 and more to customise your embedded browser. The embedded browser enables you to perform the following tasks in your JavaFX applications: Render HTML content from local and remote URLs Obtain Web history Execute JavaScript commands Perform upcalls from JavaScript to JavaFX Manage web pop-up windows Apply effects to the embedded browser  I am going to provide and explain you a sample example to create your embedded browser. This is a JavaFX sample example. if you want to take an introduction about JavaFX please visit my previous blog . I have use IntelliJ Idea IDE for this example. You can visit this link  to understand how to create JavaFX application. I am attaching the project structure image below- In this sample- we have two java class. ...

Working with MPAndroidChart (how to create Bar Chart using MPAndroidChart)

Hi Friends, In this tutorial i am going to show, "How to create Bar Chart using MPAndroidChart". There is a lot of libraries for creating charts in android like AChartEngine, MpAndroidChart, AndroidPlot etc. Your first question may be, Why MPAndroidChart. So MpAndroidChart provides better animation functionality and easy to use in comparision. Using  MPAndroidChart library  we can draw a: ·          Simple Bar Chart ·          Grouped Bar Chart ·          Horizontal Bar Chart ·          Simple Line Chart ·          Line Chart with Cubic Lines ·          Grouped Line Chart ·          Combined Line and Bar Chart ·          Pie Chart ·...