Issue with loading cellTemplate in Angular ngx-datatable

Looking to customize the template of an ngx-datatable cell, I decided to create a small view in my HTML file. To check if the template is functioning correctly, I included some placeholder text within it:

<ngx-datatable
    class="material"
    [rows]="rows"
    [columns]="columns"
    headerHeight="45">
</ngx-datatable>
<ng-template #roleTemplate let-row="row" let-value="value" let-i="index">
  <strong> **{{ value }}** </strong>
</ng-template>

Using ViewChild in my component, I obtained the template and assigned it to the datatable.

@ViewChild('roleTemplate') roleTemplate: TemplateRef<any>;

public columns = [
        { name: 'Name', prop: 'displayName' },
        { name: 'Email', prop: 'emailAddress' },
        { name: 'Role', prop: 'role', cellTemplate: this.roleTemplate },
        { name: 'Status', prop: 'status' },
    ];

Despite following the documentation, which mentions:

cellTemplate: TemplateRef

Angular TemplateRef allowing you to author custom body cell templates

The customized template does not seem to be working as expected. Is there something I might have overlooked?

Answer №1

It may be beneficial to relocate your columns initialization within the ngOnInit method, as shown below:

ngOnInit() {
  this.columns = [
    { name: 'Name', prop: 'displayName' },
    { name: 'Email', prop: 'emailAddress' },
    { name: 'Role', prop: 'role', cellTemplate: this.roleTemplate },
  ];
}

Check out this Plunker example for reference.

Answer №2

To properly set up your columns, make sure to initialize them within the ngAfterViewInit lifecycle hook. I encountered a similar issue where the templateRef was undefined even though I had initialized the columns in the ngOnInit method. I resolved this by moving the column initialization logic to the ngAfterViewInit method, which solved the problem effectively. Here's an example of how to do it in Angular 9:

import { ... AfterViewInit } from '@angular/core';

ngAfterViewInit() {
    this.columns = [
        { name: 'Name', prop: 'displayName' },
        { name: 'Email', prop: 'emailAddress' },
        { name: 'Role', prop: 'role', cellTemplate: this.roleTemplate },
        { name: 'Status', prop: 'status' },
    ];
}

Answer №3

Encountering the same issue on Angular 7 with identical sample code was a frustrating experience for me as well. Despite attempting to modify the column population within the ngOnInit method, I did not observe any improvements. Surprisingly, what ultimately resolved the problem for me was restarting the web server. Simply terminating the existing ng serve process and initiating it again seemed to eliminate the issue. Though unconventional, this approach proved effective in resolving what appeared to be a caching-related complication.

Answer №4

The issue lies in the fact that you are likely utilizing a nested template, causing Angular to struggle in obtaining a reference.

To resolve this problem, simply move your column templates as indicated below:

<ng-template #someParent>
  <ng-template #columnXYZ></ng-template>
</ng-template>

to the following location:

<ng-template #someParent></ng-template>
<ng-template #columnXYZ></ng-template>

Answer №5

The issue lies in combining initialization and assignment of a variable into one line.

public columns = [
    { name: 'Name', prop: 'displayName' },
    { name: 'Email', prop: 'emailAddress' },
    { name: 'Role', prop: 'role', cellTemplate: this.roleTemplate },
    { name: 'Status', prop: 'status' },
];

To resolve this, split the initialization and assignment onto separate lines like below:

columns: any[];


ngOnInit(): void {
    this.columns = [
        { name: 'Name', prop: 'displayName' },
        { name: 'Email', prop: 'emailAddress' },
        { name: 'Role', prop: 'role', cellTemplate: this.roleTemplate },
        { name: 'Status', prop: 'status' }
    ];
}

Answer №6

To avoid the error "NG0100: Expression has changed after it was checked," it is recommended to initialize the columns using ngAfterViewInit along with utilizing the Promise object.

ngAfterViewInit() {
    Promise.resolve().then(() => {
        this.columns = [
            { name: 'Title', prop: 'displayName' },
            { name: 'Email Address', prop: 'emailAddress' },
            { name: 'Role', prop: 'role', cellTemplate: this.roleTemplate },
        ];
    });
}

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

Developing a custom HTTP request class in Angular 2 and its exporting capabilities

I have created a simple HTTP requests class using Angular 2: http-handler.ts import {Http, Headers, RequestOptions} from 'angular2/http' import {Injectable} from 'angular2/core'; import 'rxjs/add/operator/toPromise'; @Injec ...

Steps for creating user accounts and saving user information in Firebase's Real Time Database

Can someone please guide me on how to register a user in Firebase and save their additional details such as first name, last name, etc.? I have created a standard registration form in Angular and successfully registered users with their username and pass ...

Can you assign a HostListener to a particular button in Angular application?

Whenever the ESC key is pressed, I want to invoke a specific method. This is how I currently have it set up: @HostListener('window:keydown', ['$event']) clickEscape(event: KeyboardEvent) { //if ESC was pressed if(event.keyCode ...

Troubleshooting React child problems in TypeScript

I am facing a coding issue and have provided all the necessary code for reference. Despite trying numerous solutions, I am still unable to resolve it. export class JobBuilderOptimise extends React.Component<JobBuilderOptimiseProps & JobBuilderOptim ...

The concept of HttpClient type safety appears to neglect the use of interfaces

TL;DR: A specific angular interface was linked to HttpClient.get() responses. The responses were transformed into a seemingly general object type. Even though attributes like id and title were not defined on the interface, they were still accessible in t ...

Unknown Element Error in Angular

Currently, I am working with Angular and Electron. I have successfully included ngx-quill in my module file. @NgModule({ imports: [ ~~~, QuillModule ], exports: [RouterModule] }) In addition, I have imported Quill into my main component file im ...

Exploring a collection of objects in your Angular 4 Firebase database via iteration

I've encountered some errors while attempting to iterate through my database. Despite trying various solutions, I have been unable to resolve the issue. Below you can find snippets from my code: order-details.component.html <header class="masth ...

Angular is giving me a hard time setting my background image

I'm having trouble getting the background image to load on my page. No matter what I try, it just won't show up. Here's the code snippet for my page: <div class="container" [ngStyle]="{'background-image': getUrl()}"> < ...

Expansive Carousel Feature with Ng Bootstrap

In my Angular 5 application, I am utilizing the Carousel component from "@ng-bootstrap/ng-bootstrap": "^1.1.2". I am trying to display pictures in full screen but when I press F11, the image appears like this. I am unsure of which CSS properties to apply ...

Angular error code TS2322: Type 'Promise<Dish[]>' is causing issues

I am currently learning Angular 5 on Coursera and facing an issue with the Promise concept. I followed the code from my instructor but encountered an error TS2322 while working on my service file. import { Injectable } from '@angular/core'; impo ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

Utilizing external imports in webpack (dynamic importing at runtime)

This is a unique thought that crossed my mind today, and after not finding much information on it, I decided to share some unusual cases and how I personally resolved them. If you have a better solution, please feel free to comment, but in the meantime, th ...

Building a reusable Button component in React using TypeScript that handles not assignable type errors

Attempting to create a reusable component in reactjs using typescript is currently resulting in the following error: Type '{ children: string; type: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButt ...

Applying agGroupCellRenderer alongside a personalized cell rendering feature in Angular 9

I am looking to implement a custom cell renderer on a column that has the colDef with rowGroup = true. However, I am facing an issue where the content from the html template of the cell renderer framework is not displaying as expected. Interestingly, when ...

Update a specific form data field within an Angular application

I recently encountered a situation where I had an angular form with 9 fields and submitted it to the server using a post request. However, I realized that I had only filled in values for 8 fields while leaving one as null. Now, in a new component, I am w ...

Transferring documents from an angular ionic application to a slim php framework on the localhost

Hey there! I've got a project on my localhost where I need to upload files to a local folder. I'm sharing the code here in hopes that someone can assist me. HTML: <ion-item ion-item *ngFor="let item of lista" menuClose> Floor: ...

Error: Virtual script not located; possibly absent <script lang="ts" / "allowJs": true / within the jsconfig.json.volar

https://i.sstatic.net/dFaVQ.png I noticed an error in my footer component in VueJs (TypeScript template) as depicted by the image showing blue squiggly lines. ...

Utilizing the power of Angular 15 in conjunction with Bootstrap 5's SCSS

After recently updating to Angular 15 with Bootstrap 5, I noticed that none of my utility classes are working (e.g. mb-3, mt-5, etc.) when including bootstrap in my styles.scss as shown below. @import 'bootstrap/scss/bootstrap.scss'; I understan ...

Tips for creating an array that aligns with the keys of a type in TypeScript

Currently, I am utilizing the Kysely SQL builder for JS based on Vercel's recommendation, despite the limited documentation and community support. This SQL builder is fully typed, allowing you to create a db object with a schema that recognizes table ...

Nestjs opts to handle invalid routes by throwing a NotFoundException rather than a MethodNotAllowed

I've recently developed a Rest API using NestJS and now I'm focusing on customizing error responses. Specifically, I want to address the scenario where a user calls an endpoint with the incorrect HTTP method. Take for instance the endpoint GET / ...