Tips for incorporating buttons into columns on ng2-table within Angular 2

I am in need of a table with an edit button in every column using ng2. However, I have encountered an issue placing the buttons at the end of each column.

Here is my HTML code:

<ng-table [config]="config.sorting"
      (tableChanged)="onChangeTable(config)"
      [rows]="rows" [columns]="columns" >
</ng-table>

And here is my TypeScript code:

rows: Array<any> = [];
columns: Array<any> = [
    {title: 'Name', name: 'accountname'},
    {title: 'Position', name: 'email', sort: false},
    {title: 'Office', name: 'phone', sort: 'asc'},
];

I wish to add an edit and delete button to each column. Can anyone provide guidance on how to achieve this?

Answer №1

To achieve this functionality, we can utilize Jquery library.

All we need to do is include an additional field named "Action" in the public column array.

Next, we append a new action which consists of a string of HTML code containing buttons.

constructor(private moduleviewservice:ModuleViewService,private _router:Router){
        this.moduleviewservice.getModule().subscribe(
            data=>{
                this.model=data;  
                  this.data=data;
                    for(let i=0;i<data.length;i++){
                        this.data[+i]["action"]="<a> <span class=\"viewEmployee\" data-id="+data[+i].moduleId+"> <i class=\"fa fa-file-text\"  ></i> </span> </a> <a > <span class=\"editEmployee\"  data-id="+data[+i].moduleId+"> <i class=\"fa fa-pencil\" ></i> </span> </a> <a > <span class=\"deleteEmployee\"  data-id="+data[+i].moduleId+"> <i class=\"fa fa-trash-o\" ></i> </span> </a>";
                    }
                    this.length = this.data.length;  
                    this.data=data;                 
                    console.log(this.data);
                    
                    this.onChangeTable(this.config);            
        });   
    }
    /*NG@ TABLE */

   public columns:Array<any> = [
        {title: 'Module Name', name: 'moduleName'},
        {title: 'Module Description', name: 'moduleDesc',},            
        {title: 'Action',   name:'action', sort:false},   
  ];
  
  /*IN NG ON INIT I have used this to call in (jquery)*/
  
   ngOnInit(){
        let route=this._router;
            let moduleviewservice=this.moduleviewservice;
            $(document).on('click','.viewEmployee',function(data:any){
              
              let j=$(this).attr('data-id');
              moduleviewservice.putSingleId(j);
               route.navigate( ['/home', {outlets: {'menu': 'home/singleViewModule'}}]);
            });
            $(document).on('click','.editEmployee',function(data:any){
              let j=$(this).attr('data-id');
              moduleviewservice.putSingleId(j);
               route.navigate( ['/home', {outlets: {'menu': 'home/editModule'}}]);
            });
            $(document).on('click','.deleteEmployee',function(data:any){
              let j=$(this).attr('data-id');
              moduleviewservice.putSingleId(j);
               route.navigate( ['/home', {outlets: {'menu': 'home/deleteModule'}}]);
            }); 
    }
This implementation will ensure proper display and functioning of the actions. https://i.sstatic.net/AKZuo.png

Answer №2

To easily add a button, simply insert it into the rows[] array:

rows = [{
  id: '1',
  title: 'title test1 <button type="button" class="btn btn-primary">Test Button in ng2-table</button>'
}, {
  id: '2',
  title: 'title test2'
}, {
  id: '3',
  title: 'title test3'
}]

The button will be displayed in the second column of the first row. Check out a live demo here:

You can actually insert any component into your table using this method (as long as it works with angular!)

Answer №3

After encountering the same issue, I eventually discovered a solution. If you're looking for the best data table to use with angular 2, I highly recommend checking out PRIMENG.

This powerful tool offers a wide range of features, including pagination, search, filtering, sorting, and the ability to add custom actions to each row. I urge you to give it a try!

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

Having trouble with importing and receiving the error message "Module 'clone' not found."

When trying to use clone.js in Angular 2, I imported it with import * as clone from 'clone'. It was listed in my package.json dependencies and successfully imported into node_modules. However, when viewing the output, I encountered the error mes ...

Using Laravel 5.2 passport for secure authentication with Angular 2

Being new to Laravel Passport, I find it quite confusing. I've watched Taylor Otwell's tutorial on Passport but still can't figure out if it's possible to authenticate an Angular app with Laravel Passport. My goal is to develop a Full ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

Issue with building Webpack React Router DOM configuration

I recently developed a React+Typescript app with Webpack 5 configuration completely from scratch. Everything was running smoothly in development mode, and I utilized React Router DOM version 6.23.1 for routing. However, once I built the app, some component ...

Angular: Enable function to await Observable completion before returning result

I require assistance with the user function below: getUser(uuid: string): Observable<WowUserDataModel> { let user: WowUserDataModel = { login: null, userUuid: uuid, firstName: null, lastName: null, displayName: nul ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

Encountered an issue when attempting to access a user's full details page in Angular 14

An error occurred in main.ts at line 6: TypeError - Cannot read properties of undefined (reading 'id'). The issue is located in the ContactUserDetailsComponent_Template in contact-user-details.component.html at line 17. This error is being hand ...

Trigger a (click) event on the MatTab in Material design

I have a dynamic loop through tabs and I want to be able to trigger a (click) event in order to load different options when a tab is selected. Is it not possible to use a simple click event on dynamically created tabs? I tried using (selectChange) on the ...

Trouble with Displaying Events on React Big Calendar with Typescript

Struggling to implement React Big Calendar with TypeScript. Managed to get the calendar to display correctly after adjusting the height, but unable to show any events. The array of events is populating as expected, and I modified the code for TypeScript co ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...

Angular failing to render data in user interface

Exploring the concept of CRUD Operations, I am attempting to implement basic CRUD operations using Angular for the front end and Web API for the back end. The API is quite straightforward, returning a simple JSON structure as shown below: [ { "stud ...

A guide on dynamically adding a CSS stylesheet to an Angular component during runtime

I have a requirement to dynamically inject a stylesheet into a component at runtime. The CSS url needs to change depending on user configuration settings and the selected theme. Using styelUrls for static injection won't work in this case, as it is s ...

Testing Angular: Implementing Mock Classes and Services using the Any Data Type

When mocking services without using TestBed and instead relying on Fake Classes, is it considered a best practice to use a Mock with the : any data type? If not, errors like missing items/parameters may occur. Although spyOn can be used as an alternative, ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Angular onscroll event creating a parallax effect

I attempted to create a parallax effect using Angular and the OnScroll event, however, while scrolling, the text seems to be flickering. Is there a way to make the smooth rendering onscroll? Maybe through CSS alone? Here is the script I used: https://sta ...

Steps for transferring an uploaded .CSV file to a Web service

I'm exploring the process of sending a file uploaded from the UI (angular) to a .NET web service in order for it to parse a CSV file and create a list of objects. My current understanding of the logic flow is: File upload ---> Web Service (parse ...

The collaboration of React hooks, typescript, mongoose, express, and socket.io in perfect harmony

I am currently working on setting up a frontend React app to communicate with a NodeJS Express API using socket.io import React, { useEffect, useState } from "react"; import io from "socket.io-client"; const socket = io("http://lo ...

Analyzing the elements of an array in JavaScript and making modifications to it based on their values

Looking for a Solution Current Data- id price 1001 200 1001 150 1002 300 1003 50 1002 70 1004 30 Desired Outcome id price 1001 350 1002 370 1003 ...

Protractor's slow performance is due to continually checking for elements that do not exist

Currently, I am in the process of writing end-to-end tests for a rather extensive Angular 4 project. In order to handle the closing of a modal dialog (if it happens to be present), I have created a helper function. Due to certain conditions that may automa ...

Update the color of the label on the ng2-charts/charts.js pie chart

I am currently using ng2-charts and have successfully created a beautiful pie-chart with labels and data. However, I am unable to change the default grey color of the labels. Is this normal? How can I override the default label color? It appears that the ...