Incorporate a personalized button within the actions column of ng2-smart-table for Angular 2 development

Within the context of an ng2-smart-table component in Angular 2, I am attempting to include a new button within the actions column that, when clicked, will navigate to another page. Despite my efforts to implement this new button alongside the existing add, edit, and delete buttons, I have encountered some challenges:

settings = {

    add: {
      addButtonContent: '<i class="ion-ios-plus-outline"></i>',
      createButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent: '<i class="ion-close"></i>',
      confirmCreate: true
    },
    edit: {
      editButtonContent: '<i class="ion-edit"></i>',
      saveButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent: '<i class="ion-close"></i>',
      confirmSave: true
    },
    delete: {
      deleteButtonContent: '<i class="ion-trash-a"></i>',
      confirmDelete: true
    }, 

I am seeking guidance on how to successfully integrate this new button into the table. Upon consulting the available documentation, I was unable to locate any relevant information pertaining to this specific requirement.

Answer №1

In my List module

actions: {
      columnTitle: 'Actions',
      add: false,
      edit: false,
      delete: true,
      custom: [
      { name: 'viewdata', title: '<i class="fa fa-eye"></i>'},
      { name: 'editdata', title: '&nbsp;&nbsp;<i class="fa  fa-pencil"></i>' }
    ],
      position: 'right'
    },

Next, in the template

<ng2-smart-table class="table table-hover" [settings]="configurations" [source]="datasource"
   (deleteConfirm)="onDeletionConfirmation($event)"  (custom)="onCustomEvent($event)">
  </ng2-smart-table>

This function helped me determine which custom action to perform.

onCustomEvent(event) {
      switch ( event.action ) {
        case 'viewdata':
          this.viewData(event.data);
          break;
       case 'editdata':
          this.editData(event.data);
      }
    }

public editData(formData: any) {
      this.modalRef = this.modalService.open(EditProfileModule);
      this.modalRef.componentInstance.formData = formData;
      this.modalRef.result.then((result) => {
        if (result === 'success') {
          this.loadInformation();
        }
      }, (reason) => {
      });
    }

public viewData(formData: any) {
      this.modalRef = this.modalService.open(ViewProfileModule);
      this.modalRef.componentInstance.formData = formData;
      this.modalRef.result.then((result) => {
        if (result === 'success') {
          this.loadInformation();
        }
      }, (reason) => {
      });
    }

Answer №2

Give it a shot:

To customize your columns, include a new column named "Actions":

  Actions: //or something
  {
    title:'Details',
    type:'html',
    valuePrepareFunction:(cell,row)=>{
      return `<a title="View Product Details "href="Your secret api key or unique identifier/${row.Id}"> <i class="ion-edit"></i></a>`
    },
    filter:false       
  },
  Id: { //utilize this Id within ${row.Id}
    title: 'Identifier',
    type: 'number'
  },

Answer №3

I encountered a similar issue and managed to resolve it by using a custom action approach, inspired by this example: basic-example-custom-actions.component

Here are the settings I implemented:

actions: {
  add: false,
  edit: false,
  delete: false,
  custom: [{ name: 'ourCustomAction', title: '<i class="nb-compose"></i>' }],
  position: 'right'
},

In the template: I defined the function associated with our custom action

<ng2-smart-table #ourTable [settings]="settings" [source]="source"
    (custom)="onCustomAction($event)">

A router is required for redirection:

import {Router} from '@angular/router';
...
constructor(private router: Router) {}

Subsequently, we can navigate to another page as needed:

onCustomAction(event) {
  // alert(`Custom event '${event.action}' fired on row №: ${event.data.id}`);
  this.router.navigate(['pages/ourPage']);
}

The same concept can be applied when a user clicks on a row:

(userRowSelect)="onCustomAction($event)"

Edit: To customize the style, refer to the following example:

Add to component.css

To ensure our custom button fits correctly within the table row, we need to adjust the default styling of the edit and delete elements.

:host ::ng-deep .ng2-smart-actions ng2-st-tbody-edit-delete {display: none !important;}

:host ::ng-deep ng2-st-tbody-custom a.ng2-smart-action.ng2-smart-action-custom-custom {
    display: inline-block;
    width: 80px;
    text-align: center;
    padding-top: 10px;
}

Answer №4

To customize your ng2-smart-table, add the following code to your settings file:

actions: {
  edit: false, //for example
  custom: [{ name: 'routeToAPage', title: `<img src="/icon.png">` }]
}

You now have a custom button called routeToAPage with an image on it.

Next, include this in your ng2-smart-table tag:

<ng2-smart-table [settings]="settings" [source]="dataSource" (custom)="route($event)"></ng2-smart-table>

Create a route function to handle the custom action as needed.

Answer №5

If you're still on the quest for a solution, I too encountered the same issue and was unable to resolve it.

Going back to version 1.1.0 (as specified in your package.json) did the trick for me! I also noticed that the buttonContent tag works well for Edit and Delete buttons but not for Add.

Let's hope this bug gets sorted out soon.

Answer №6

Within an HTML template, you have the ability to subscribe to edit and delete events:

<ng2-smart-table [settings]="settings" [source]="source" (edit)="onEdit($event)" (delete)="onDelete($event)"></ng2-smart-table>

Your onEdit and onDelete functions can be customized to make changes as needed.

I trust this information is helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...

Angular 2 regex for validating FQDN/URL formats

As a beginner in regex, I'm looking for help with validating fully qualified domain names (e.g. mysite.com) or a URL without checking the protocol. Can anyone provide a regex expression or suggest where to find one? ...

Encountering issues with app functionality following update to Ionic RC4 version

Since upgrading from Ionic rc3 to rc4, I've been facing difficulties running my app smoothly. The app compiles without any errors when I use ionic-app-scripts build --prod, but when I try to run it on my iPhone, all I get is a blank screen and an err ...

Table with a responsive c3 chart

Is there a way to integrate a responsive C3 chart into a table? I am trying to set up a table with a responsive layout, where one of the cells contains a C3 chart. The initial dimensions of the cell are 200 width and 50 height, but I want the chart to upd ...

Is there a way to imitate a method that initiates an AJAX request?

I am currently working on writing tests for my Angular application and I need to mock a method in order to avoid making actual requests to the server. Within my grid.service.ts file, here is the method I am trying to mock: loadAccountListPromise(id: str ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

Implementing Limited Results in Redis FT.SEARCH with TypeScript

Snippet of code: client.ft.SEARCH('license-index-json',"@\\$\\" + ".reservedForApplicationName:GSTest",{ LIMIT: { from: 0, to: 1 } }) Error message: An error occurred when trying t ...

ngx-infinite-scroll event fails to trigger upon scrolling to the end

I am currently facing an issue while trying to implement infinite scroll using ngx-infinite-scroll in an Angular 4 application. Despite following the documentation and configuring the height of the element while setting scrollWindow to false, the trigger i ...

Having trouble migrating Angular with Nativescript? Encounter an issue parsing the angular.json file

Attempting to enhance Angular with Nativescript by following the provided instructions has led to a puzzling issue. Whenever the command to add nativescript-schematics (ng add @nativescript/schematics) is executed, an error message stating "File angular.js ...

Error: Cannot modify the constant property 'name' of the function."&squo;

As I attempted to enter text into the input box, an error message appeared after typing my first letter stating "cannot assign to read only property". Below is the code I am referring to: The code of the component can be found here: https://i.sstatic.net ...

How can you determine the type of an argument based on the type of another argument?

Is it possible to dynamically assign value types in the const set = (key: keyof Store, value: any) function based on the keys defined in the Store interface? For instance, setting a key foo as type number and key bar as type string[]. import store from & ...

Exploring the Power of SectionList in Typescript

How should SectionList be properly typed? I am encountering an issue where this code works (taken from the official documentation example): <SectionList renderItem={({item, index}) => <Text key={index}>{item}</Text>} renderSectionHea ...

What are the steps to display Firestore data on the server instead of the client side?

My objective is to display data on the server side. Expected outcome: the server should render the data. Actual outcome: the data is being rendered by the client instead of the server. The workflow follows this pattern Component -> call Use Case -> ...

Trouble Getting formGroup to Function Properly with Radio Button in Angular 2

Is there a way to pass the rating value from my template to my component without using parameter passing in a method? Currently, I am passing it as a parameter in the following manner: <form [formGroup]="ratingForm"> <div *ngFor=" ...

Automatically encapsulate Typescript definition files within modules

There seems to be a missing tsconfig option in my setup. Here's what I'm trying to do: I'm developing an npm module, such as: export class HelloWorld { constructor(public greeting: string){} } with the following tsconfig settings: { ...

Notifying Subscribed Angular8 Components Based on Logical Conditions with Observables Inside Services

I provide a service that offers a function returning an Observable. Within this service, I have certain logic that should trigger a new call on the Observable to update the data for subscribed components. While I can use next within the Observer construct ...

Can anyone provide a solution for fixing TypeScript/React error code TS7053?

I encountered an error message with code TS7053 which states: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'. No index signa ...

Using TypeScript and HTML to toggle a switch and retrieve its value

I am currently trying to utilize a toggle switch to determine which methods need to be activated. My expectation is that I can obtain a Boolean value indicating whether the switch is turned on or off. However, I am unsure of how to retrieve this informatio ...

Navigating data flow between tabs in Ionic

I am working on a straightforward project that involves 3 tabs. One of the requirements is to move an item from the first tab to the second tab and vice versa when a button is clicked, with a notification sent to the server upon this action. Is there a way ...

How to conceal an element in Angular using its unique identifier

I am looking for a way to toggle the visibility of an element based on its ID. I have a dynamic list with the following structure in my TS component: vehicles = [ { "id": 1, "type": "car", ...