How can I add a JavaScript-created element into a Primeng TurboTable component?

I am in the process of replacing a custom-made table with PrimeNG's turbotable. The issue I'm facing is that when I try to insert buttons into the table that call specific JavaScript functions, they end up displaying as [object HTMLInputElement] rather than actual buttons. This problem seems to occur because the turbotable converts the element into text instead of rendering it as HTML.

Here is an example of what is being displayed:

Below is the code for the turbotable:

<p-table [columns]="resultsCols" [value]="results">
  <ng-template pTemplate="caption">
    Agencies  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Count {{results?.length}}
  </ng-template>
  <ng-template pTemplate="header">
    <tr>
      <th >Options</th>
      <th [pSortableColumn]="'agency'" >Agency</th>
      <th [pSortableColumn]="'department'" class="ui-p-2">Department</th>
      <th [pSortableColumn]="'affiliateCount'" class="ui-p-4">Affiliate Count</th>
      <th [pSortableColumn]="'basigdate'" class="ui-p-6">BA Sig Date</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-r>
    <tr>
      <td>  {{r.btnEdit}}</td>
      <td >{{r.agency}}</td>
      <td class="ui-p-2">{{r.department}}</td>
      <td class="ui-p-4">{{r.affiliateCount}}</td>
      <td class="ui-p-6">{{r.basigdate}}</td>
    </tr>
  </ng-template>
</p-table>

Here is how the button is generated and the results array populated:

var result = JSON.parse(xmlhttp.responseText);

for (var i = 0; i < result.length; i++) {

  var inputEdit = document.createElement("input");
  inputEdit.type = "button";
  inputEdit.value = "Edit";
  inputEdit.classList.add("btn-link");
  inputEdit.onclick = (
    function(i) {
      return function() {
        comp.setEditMode(i);
      }
    }
  )(result[i].id);


  var a = new agencySearchResult();
  a.agency = result[i].name;
  a.affiliateCount = result[i].affiliateCount;
  a.basigdate = result[i].baSigDate;
  a.department = result[i].department;
  a.btnEdit = inputEdit;

  comp.results.push(a); 
}

Finally, this is where the agencySearchResult class is defined in TypeScript:

export class agencySearchResult {
  constructor() {};

  agency: string;
  department: string;
  affiliateCount: string;
  basigdate: string;

  btnEdit: HTMLInputElement;
}

I suspect that the issue lies in the {{r.btnEdit}} line in the HTML code, but I have included all relevant information just in case. Can anyone provide guidance on how to properly insert a JavaScript-generated HTML element into a turbotable?

Answer №1

You might want to consider placing your HTML button within your component file rather than creating it in your TypeScript code.

Instead of:

<td>  {{r.btnEdit}}</td>

and

var inputEdit = document.createElement("input");
  inputEdit.type = "button";
  inputEdit.value = "Edit";
  inputEdit.classList.add("btn-link");
  inputEdit.onclick = (
    function(i) {
      return function() {
        comp.setEditMode(i);
      }
    }
  )(result[i].id);

You can replace them with something like:

<td><input type="button" value="Edit" class="btn-link" (click)="edit(r.id)"/></td>

and

edit(rowId) {
    alert('Edition of row ' + rowId);
    // do whatever you need
}

This approach is more concise and easier to read.

Check out this StackBlitz for reference.

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

Is there a way for me to deduce types dynamically?

Is there a way to dynamically infer types, similar to a union type? I am trying to register multiple elements from different parts of the code using a method like registerElement(...), but I am struggling with inferring these new types in TypeScript. This ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Troubles arise with a Web API ASP .NET / Angular2 Session hosted on Azure

Hello, this is my first question here so please let me know if something doesn't fit. Currently, we are working on developing a Web API using C# and Angular2. One of the features requires the session to be efficient, but despite going through numerou ...

Testing the functionality of an Angular service using unit tests

Confused about how to test a service in an Angular project that involves a small class with an observer? Can't seem to figure out why the test fails when calling the 'pop' method. Want to ensure that the public methods of this class perform ...

accessing observables programmatically in Angular 5 using a service getter

Assistance Needed with Service Component ... cart: any = {...}; //observable set in a subscription to an API response get Cart() { return this.cart; } ... Problem with Component Implementation get Cart() { return this.bcCartService.Cart; } constru ...

issue with ng2-semantic-ui: remote options not properly loading in select

public optionsLookup(query:string, initial:any): Promise<any> { return new Promise ( (resolve, reject) => /*[{ id: 1, name: 'ololo1'}, { id: 2, name: 'ololo2'}]*/ this.apiService.get('private/count ...

Encountering a challenge in Angular 8: Unable to locate a supporting object matching '[object Object]'

I am having an issue trying to retrieve the Spotify API from the current user's playlists. While I can see it in my console, when I attempt to insert it into HTML, I encounter the following error: ERROR Error: Cannot find a differ supporting object ...

Learn how to use the rendertron middleware in Node.js Express to redirect all routes to the original Angular app

Currently, I am working on creating a rendertron middleware using nodejs to determine when to utilize pre-rendered content and when to use the original application. However, I am facing challenges in redirecting to my usual Angular app using fetch or any o ...

Preventing Page Refresh when Button is Clicked in Angular

How can I prevent page reload when a button is clicked in Angular? I'm developing a quiz application in Angular where I fetch random questions and options from an API. When users select an option, the next question should appear without reloading the ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Gathering user key event input for a duration of 2 seconds before resetting it

I need help implementing a feature where I can clear the user's input text after 500ms if they are entering characters consecutively. private userInputTimer; private userInputText = ''; private handleEvent(event: KeyboardEvent): void { if ...

What is the best way to implement a comprehensive switch case in Typescript using string enums that are referencing other string enums?

I am faced with a challenge where I have a subset of values from one enum that I need to switch case across in TypeScript. Here's an example to illustrate my dilemma: const enum Fruit { APPLE = 'Apple', BANANA = 'Banana', ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

Solution for primeNG dataTable with colspan in the tbody area

Encountering a common issue where you need a col span for tbody instead of just headers provided in the PrimeNG Documentation. I attempted to add it programmatically using directives and JavaScript. Below is an example of the code. While this solution ma ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

Instead of relying on the valueChanges method, consider using setValue or patchValue in Angular 4 to monitor

I've implemented a floating point directive on fields in a reactive form to enhance readability by adding commas every 1000 and appending .00 to field values. This formatting works well, with onBlur triggering the formatting and onFocus removing it. ...

Experiencing a compilation issue while attempting to apply the class-transformer

Encountering an issue while working with a basic example that involves class-transformer. error TS1240: Unable to resolve signature of property decorator when called as an expression. Argument of type 'ClassFieldDecoratorContext<Root, Project[]> ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...