npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-table-pro

v0.0.0-watch

Published

`NgxTablePro` is an advanced Angular library for creating interactive and highly customizable tables. This library is generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.3.0 and is designed to be integrated into any Angular pro

Downloads

8

Readme

NgxTablePro

NgxTablePro is an advanced Angular library for creating interactive and highly customizable tables. This library is generated with Angular CLI version 17.3.0 and is designed to be integrated into any Angular project seamlessly.

Features

  • Crud Operation: Allows Save, Edit, Discard, and Delete
  • Fully Customizable: Style and configure tables to meet the specific needs of your application.
  • Responsive Design: Supports resizable columns on drag to ensure your tables look great on any device.
  • Server-Side Operations: Efficiently manage data with options for server-side pagination and sorting.
  • Client-Side Operations: Quickly sort and paginate data on the client side for fast interactions.
  • Inline Editing: Edit data directly within the table for a seamless user experience.
  • Row Validation: Ensure data integrity with built-in validation options.
  • Multiple Row Selection: Supports shift selection, control selection, and single selection for versatile data manipulation.
  • Custom Actions: Provide hooks for custom actions to extend functionality.
  • Flexible Data Sources: Integrate with various data sources for maximum flexibility.

Installation

Install ngx-rich-text-editor via npm:

`npm i ngx-table-pro

Import the Material theme CSS and Font Awesome CSS in your project's styles.css file

@import 'font-awesome/css/font-awesome.min.css';

@import '@angular/material/prebuilt-themes/indigo-pink.css';

Add BrowserAnimationsModule and NgxTableProModule in your app.module

import { NgxTableProModule } from 'ngx-table-pro';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';


@NgModule({
  declarations: [
    // other components
  ],
  imports: [
    BrowserAnimationsModule,
    NgxTableProModule
    // other modules
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Usage

This guide provides step-by-step instructions on how to set up a basic data table using the NgxTablePro Angular component. This example includes configuration for columns, pagination, and the ability to highlight multiple rows.

Step 1: Define the Table in Your Template

First, include the lib-generic-data-table in your component's HTML template with the necessary configuration parameters. Here's a simple setup:

<lib-generic-data-table
  [dataSource]="dataSource"
  [columns]="columns"
  [totalItems]="dataSource.length"
  [isServerSidePagination]="false"
  [isServerSideSorting]="false"
  [showPagination]="true"
  [enableMultiRowHighlight]="true"
></lib-generic-data-table>

Step 2: Configure Columns

Define the configuration for your table's columns in the component's TypeScript file. Here's an example of a simple column setup:

columns = [
  { field: 'id', label: 'ID', width: 50 },
  { field: 'name', label: 'Name', width: 150 },
  { field: 'username', label: 'Username', width: 100 },
  { field: 'email', label: 'Email', width: 200 }
];

Step 3: Initialize the Data Source

Populate your table with some dummy data by initializing the dataSource in your component:

dataSource = [
  { id: 1, name: 'Alice', username: 'alice123', email: '[email protected]' },
  { id: 2, name: 'Bob', username: 'bob456', email: '[email protected]' },
  { id: 3, name: 'Charlie', username: 'charlie789', email: '[email protected]' }
];

NgxTablePro Component Configuration

This section details the configurable properties of the NgxTablePro component, allowing developers to understand how to customize the table according to their requirements.

Template

<lib-generic-data-table
  [dataSource]="dataSource"
  [columns]="columns"
  [totalItems]="dataSource.length"
  [isServerSidePagination]="false"
  [isServerSideSorting]="false"
  [showPagination]="true"
  [enableMultiRowHighlight]="true"
></lib-generic-data-table>

Properties

[dataSource]

  • Type: Array<object>
  • Required: Yes
  • Description: An array of objects that serves as the data source for the table.

[columns]

  • Type: Array<{ field: string; label: string; width: number; editable?: boolean; editType?: string; }>
  • Required: Yes
  • Description: Defines the configuration of table columns. Each object in the array configures a column in the table.
    • field: The property name in the data source objects to display in this column.
    • label: The display label for the column header.
    • width: The width of the column in pixels.
    • editable (optional): Whether the column is editable.
    • editType (optional): Type of input control for editing. Supported values include 'input', 'textarea', 'select', etc.
    • radio (optional): A boolean that indicates whether the column will contain radio buttons for selection.

[totalItems]

  • Type: number
  • Required: Yes
  • Description: The total number of items in the data source. This is used for pagination. In case of isServerSidePagination false, use total number of records provided, else give total number of records in server

[showPagination]

  • Type: boolean
  • Default: true
  • Description: Determines whether pagination controls are displayed at the bottom of the table.

[enableMultiRowHighlight]

  • Type: boolean
  • Default: false
  • Description: Allows multiple rows to be selected/highlighted via shift and control click.

[isServerSidePagination]

  • Type: boolean
  • Default: false
  • Description: Set to true to handle pagination on the server side.

[isServerSideSorting]

  • Type: boolean
  • Default: false
  • Description: Set to true to handle sorting on the server side.

@Input() selectedRadio

  • Type: any
  • Default: -1
  • Description: Holds the currently selected item for radio button inputs. This property can be used to track and update the selected state of radio buttons within the table.

@Input() valueField

  • Type: string
  • Required: Yes
  • Description: Specifies the field within the data source items that acts as the unique identifier for radio button selection. This field determines which item is considered 'selected' based on its value.

Server-Side Pagination and Sorting

NgxTablePro supports server-side pagination and sorting, enabling efficient data management by handling large datasets through server requests based on user interactions. This feature is essential for performance in applications with substantial data, reducing the client-side load.

Implementation To implement server-side pagination and sorting, you need to add the following code snippets to your component's template and TypeScript file:

Template Modification

<app-generic-data-table
    ...
    [isServerSidePagination]="true"
	[isServerSideSorting]="true"
    (pageChanged)="pageChanged($event.pageIndex, $event.pageSize)"
    (sortChanged)="onSortChanged($event)"
    ...
</app-generic-data-table>
page: number = 1;
limit: number = 10;
sortParam: { property: string, direction: string } | null = null;

pageChanged(pageIndex: number = 0, pageSize: number = 10) {
  this.page = pageIndex + 1;
  this.limit = pageSize;
  this.refreshDataWithNewParam();
}

onSortChanged(sortParam: { property: string, direction: string } | null) {
  this.sortParam = sortParam;
  this.refreshDataWithNewParam();
}

refreshDataWithNewParam() {
  // API call to fetch data based on `this.page`, `this.limit`, and `this.sortParam`
  console.log(`Fetching data for page ${this.page} with limit ${this.limit} and sort parameter`, this.sortParam);
}

Server Side Pagination pageChanged

The pageChanged method is triggered when the user interacts with the pagination controls to switch pages. This method updates two key properties within the component:

  • page: Adjusts the current page index as selected by the user. This adjustment accounts for the difference between client-side and server-side paging conventions by offsetting the page index by one.
  • limit: Specifies the number of records displayed per page.

You can associate any function with the pageChanged hook, utilizing page and limit to effectively manage data display based on user interactions with pagination controls.

Sort Handling

The sortChanged event is triggered when sorting parameters are changed in the UI. This method accepts a parameter sortParam, which is structured as { property: string, direction: string }. The property represents the field name to sort by, and the direction specifies the sorting order (ASC for ascending, DESC for descending).

  • sortParam: Object containing the sorting criteria.
    • property: Name of the field to sort.
    • direction: Sort direction (ASC or DESC).

You can associate any function with the sortChanged hook.

Using the Properties

When pagination or sorting parameters change, the refreshDataWithNewParam() method is called. This method should contain the logic to make an API request to your backend server, passing the current page, limit, and sortParam as query parameters. The server should then return the data sorted and paginated according to these parameters, which your Angular component can then display.

Editable Fields in Data Table

Description

Editable fields in a data table allow users to modify the contents directly within the table interface. This section describes how to configure editable fields and associated actions within the Data Table component.

Configuration

columns

  • Type: Array<object>
  • Description: Array of objects that configure columns in the data table, including options for editability and input type.
  • Required: Yes

Properties for columns objects:

Editable Field Configuration

editable
  • Type: boolean
  • Default: false
  • Description: Determines if the column is editable. Set to true to enable editing.
editType
  • Type: string
  • Enum: ['input', 'dropdown']
  • Description: Specifies the type of input control used for editing. Supported values are 'input' for standard text inputs and 'dropdown' for selection from a list.
  • Required: If editable is true.

Specific Input Configurations

For editType: 'input'
type
  • Type: string
  • Enum: ['text', 'number']
  • Description: Specifies the HTML input type for the 'input' edit type, defining whether the text or a number is entered.
  • Required: Yes
min (for type: 'number')
  • Type: number
  • Description: The minimum value allowed for numeric inputs.
  • Required: No
max (for type: 'number')
  • Type: number
  • Description: The maximum value allowed for numeric inputs.
  • Required: No
For editType: 'dropdown'
options
  • Type: Array<string>
  • Description: Specifies the dropdown options available for selection.
  • Required: Yes

Action Configuration

actions
  • Type: Array<object>
  • Description: Defines actions associated with the column, such as editing, deleting, saving, or discarding changes. Includes configurations for icons and conditions under which they appear.
  • Required: Optional, typically used in a column dedicated to actions.

Example JSON Configuration

{
  "columns": [
    {
      "field": "id",
      "label": "ID",
      "editable": false
    },
    {
      "field": "name",
      "label": "Name",
      "editable": true,
      "editType": "input",
      "type": "text"
    },
    {
      "field": "quantity",
      "label": "Quantity",
      "editable": true,
      "editType": "input",
      "type": "number",
      "min": 1,
      "max": 100
    },
    {
      "field": "status",
      "label": "Status",
      "editable": true,
      "editType": "dropdown",
      "options": ["Active", "Inactive", "Pending"]
    },
    {
      "field": "actions",
      "label": "Actions",
      "actions": [
        { "name": "edit", "icon": "edit_icon", "onEdit": true },
        { "name": "delete", "icon": "delete_icon" },
        { "name": "save", "icon": "save_icon", "onEdit": true },
        { "name": "discard_changes", "icon": "cancel_icon", "onEdit": true }
      ]
    }
  ]
}

NgxTablePro Action Hooks

Overview

NgxTablePro facilitates the association of user actions with specific functions through the actionTriggered event hook. This feature enables dynamic interactions within data tables by processing user clicks and performing corresponding actions.

Setup

Integrating the Component

To utilize the action hooks, incorporate the app-generic-data-table component into your HTML and bind the actionTriggered event:

<app-generic-data-table (actionTriggered)="onActionTriggered($event)">
</app-generic-data-table>

Event Structure

The actionTriggered event outputs an object: { action: actionName, item: item }. Here, actionName is a string identifying the type of click (e.g., 'dbClick', 'multiRowClicked'), and item is the associated table row. If no specific row is involved, item will be an empty object ({}).

Configuring Action Handlers

Define a mapping of action names to functions within your Angular component using an actionsMap. This mapping allows you to specify which function to call for each action type:

actionsMap = {
  'dbClick': (item) => this.yourFunction(item),
  'multiRowClicked': (item) => this.yourFunction(item),
  'refresh': (item) => this.refreshPeriodicity(),
  // Additional custom actions can be defined here
};

onActionTriggered(event: any) {
  const actionHandler = this.actionsMap[event.action];
  if (actionHandler) {
    actionHandler(event.item);
  } else {
    console.error(`No handler for action: ${event.action}`);
  }
}

Customizing Actions

You can enhance your data table's functionality by adding custom actions to the actionsMap. Each action should have a unique identifier (actionName) and a corresponding function that defines the action's behavior.

Advanced Configuration for NgxTablePro Action Hooks

Overview

NgxTablePro integrates customizable action hooks with the data table, enabling developers to assign specific behaviors to icons or buttons directly within table rows. This setup not only simplifies interactions but also enhances the user experience by providing immediate visual cues for available actions.

Configuring Table Columns with Actions

Column Setup

To implement actions within your data table, you must define them in the columns configuration of your table setup. Each action is associated with an icon, and these icons trigger the corresponding action when clicked.

Example Configuration

Here’s how to define the actions within the columns array:

columns = [
  // Other column definitions
  {
    field: 'actions',
    label: 'Actions',
    width: 10,
    actions: [
      { name: 'edit', icon: 'nlsn:edit' },
      { name: 'delete', icon: 'nlsn:trash' },
      { name: 'save', icon: 'nlsn:toast_done', onEdit: true },
      { name: 'discard_changes', icon: 'nlsn:close', onEdit: true }
      // Additional custom actions can be added here
    ]
  }
];

Key Properties

  • name: This specifies the actionName which will be returned by the actionTriggered event when the icon is clicked.
  • icon: Indicates which icon from the font library (e.g., Font Awesome) is used to represent the action visually.
  • onEdit: A boolean that can be set to true if the action should only be available in edit mode.

Handling Actions

When an action icon is clicked, the actionTriggered event is emitted. This event returns an object containing the actionName and the item associated with the action.

Action Handling Example

Here is how you might handle actions within your component:

onActionTriggered(event: any) {
  const actionHandler = this.actionsMap[event.action];
  if (actionHandler) {
    actionHandler(event.item);
  } else {
    console.error(`No handler for action: ${event.action}`);
  }
}

Custom Actions in Columns

To add a custom action, define it within the actions array in your columns configuration and map the action in your actionsMap:

columns = [
  {
    field: 'actions',
    label: 'Actions',
    width: 10,
    actions: [
      ...,
      { name: 'customAction', icon: 'custom-icon' }
    ]
  }
];

actionsMap = {
  ...,
  'customAction': (item) => this.customFunction(item),
};

function customFunction(item) {
  // Define behavior for the custom action here
}

Overview

NgxTablePro integrates customizable action hooks with the data table, enabling developers to assign specific behaviors to icons or buttons directly within table rows. This setup not only simplifies interactions but also enhances the user experience by providing immediate visual cues for available actions.

Configuring Table Columns with Actions

Column Setup

To implement actions within your data table, you must define them in the columns configuration of your table setup. Each action is associated with an icon, and these icons trigger the corresponding action when clicked.

Example Configuration

Here’s how to define the actions within the columns array:

columns = [
  // Other column definitions
  {
    field: 'actions',
    label: 'Actions',
    width: 10,
    actions: [
      { name: 'edit', icon: 'nlsn:edit' },
      { name: 'delete', icon: 'nlsn:trash' },
      { name: 'save', icon: 'nlsn:toast_done', onEdit: true },
      { name: 'discard_changes', icon: 'nlsn:close', onEdit: true }
      // Additional custom actions can be added here
    ]
  }
];

Key Properties

  • name: This specifies the actionName which will be returned by the actionTriggered event when the icon is clicked.
  • icon: Indicates which icon from the font library (e.g., Font Awesome) is used to represent the action visually.
  • onEdit: A boolean that can be set to true if the action should only be available in edit mode.

Handling Actions

When an action icon is clicked, the actionTriggered event is emitted. This event returns an object containing the actionName and the item associated with the action.

Action Handling Example

Here is how you might handle actions within your component:

onActionTriggered(event: any) {
  const actionHandler = this.actionsMap[event.action];
  if (actionHandler) {
    actionHandler(event.item);
  } else {
    console.error(`No handler for action: ${event.action}`);
  }
}

Custom Actions in Columns

To add a custom action, define it within the actions array in your columns configuration and map the action in your actionsMap:

columns = [
  {
    field: 'actions',
    label: 'Actions',
    width: 10,
    actions: [
      ...,
      { name: 'customAction', icon: 'custom-icon' }
    ]
  }
];

actionsMap = {
  ...,
  'customAction': (item) => this.customFunction(item),
};

function customFunction(item) {
  // Define behavior for the custom action here
}

Conclusion

By configuring actions directly within the columns of your NgxTablePro setup, you create a more interactive and user-friendly table environment. This approach not only streamlines the interface but also provides clear, actionable options to the users, enhancing the overall functionality and responsiveness of your application.

Handling Actions: Save, Edit, Discard, and Delete

The NgxTablePro component enables dynamic interaction with table data, allowing users to edit, save, discard, and delete entries directly from the table interface. This section outlines how these actions are configured and handled within the component.

Action Trigger Handling

Actions are triggered through user interaction, such as button clicks. The handling of these actions is centralized through the onActionTriggered method, which dispatches the action to the appropriate handler based on the action's name:

onActionTriggered(event: { action: string, item: any }) {
  const actionHandler = this.actionsMap[event.action];
  if (actionHandler) {
    actionHandler(event.item);
  } else {
    console.error(`No handler for action: ${event.action}`);
  }
}

Actions Map

The actionsMap is an object that maps action names to their corresponding handler functions. This approach allows for modular and easy management of various actions:

actionsMap: any = {
  'delete': (item: any) => this.deleteItem(item),
  'edit': (item: any) => this.editItem(item),
  'save': (item: any) => this.saveItem(item),
  'remove': (item: any) => this.cancelEdit(item)
};

Edit Action

Marks an item as being edited and stores the original data for potential restoration: To Enable editing of a row, you have to set item.edited = true; You can access row using onActionTriggered Hook

editItem(item: any) {
  console.log('Edit operation not implemented.', item);
  this.originalRowData[item.id] = { ...item };
  item.edited = true;
} 

Validating Row Data

Before performing actions, especially for edit and save, it's crucial to validate the row data. The validateRowFunction method ensures that necessary fields are present and correctly formatted:

validateRowFunction(row: any): boolean {
  return row.firstName.length > 0 && row.email.includes('@');
}

Save Action

Finalizes the changes to an item and marks it as not being edited:

saveItem(item: any) {
  console.log('Save operation not implemented.', item);
  item.edited = false;
}

Discard/Remove Action

Cancels any changes to an item, restoring it to its original state if previously edited, or removing it if it was newly added:

cancelEdit(item: any) {
  console.log('Cancel edit operation not implemented.', item);
  if (item.isNew) {
    this.dataSource = this.dataSource.filter(row => row.id !== item.id);
  } else if (this.originalRowData[item.id]) {
    const index = this.dataSource.findIndex(row => row.id === item.id);
    this.dataSource[index] = this.originalRowData[item.id];
  }
  item.edited = false;
  this.updateDataSource(item);
}

Updating the Data Source

Reflects changes made to items back to the local data source:

updateDataSource(modifiedItem: any) {
  this.dataSource = this.dataSource.map(row => {
    if (row.id === modifiedItem.id) {
      return { ...row, edited: modifiedItem.edited };
    }
    return row;
  });
}