Passing dynamic data between TypeScript and HTML files in an Angular project

I have a grid where I need to apply conditional classes based on data from my .ts file. I was able to accomplish this using the code snippet

myClassCondition = 5 < 6 ? 'bg-red' : null;
as shown below. However, I want to achieve a similar functionality with variables "col" and "rowData". This resulted in compilation errors because "col" and "rowData" are not defined in the .ts file. How can I make this work?

<ng-template pTemplate="body" let-rowData>
  <tr>
    <td *ngFor="let col of myColumns" class="ui-resizable-column">
      <span [ngClass]="myClassCondition"> {{rowData[col.field]}}</span>
    </td>
  </tr>
</ng-template>

The current setup is functioning without any issues.

myClassCondition = 5 < 6 ? 'bg-red' : null;

However, I would like to modify it to something like this:

myClassCondition = col.field == 'studentAge' && rowData.[col.field] < 6 ? 'bg-red' : null;

Even though I attempted the modification above, it did not produce the desired outcome.

myClassCondition : string = "col.field == 'studentAge' && rowData.[col.field] < 6 ? 'bg-red' : null";

Answer №1

To enhance your ts file, consider using a function instead of a variable to determine the class.

getClassCondition(col, rowData)
{
 return col.field == 'studentAge' && rowData.[col.field] < 6 ? 'bg-red' : null;
}

In your template, utilize this function to retrieve the class,

<ng-template pTemplate="body" let-rowData>
  <tr>
    <td *ngFor="let col of myColumns" class="ui-resizable-column">
      <span [ngClass]="getClassCondition(col, rowData)"> {{rowData[col.field]}}</span>
    </td>
  </tr>
</ng-template>

If you have a separate component named app-grid and need the class name logic to be determined by the hosting component, you can implement the following steps:

In the ts file of your app-grid component, add an input to receive the function that provides the desired value,

@Input() logic: any;

Modify the getClassCondition function in the app-grid component like this,

getClassCondition(col, rowData)
{
 return logic(col,rowData);
}

In the hosting component, define the actual function that determines the class. Add it to the ts file of that component as follows,

logic = function(col,rowData){
 return col.field == 'studentAge' && rowData.[col.field] < 6 ? 'bg-red' : null; // modify this implementation in various components
}

In the template file of that component, pass this function as an input to the app-grid component

<app-grid [logic]="logic"></app-grid>

Answer №2

<ng-template pTemplate="body" let-rowData>
  <tr>
    <td *ngFor="let col of myColumns" class="ui-resizable-column">
      <span [ngClass]="applyClassCondition(rowData,col.field)"> {{rowData[col.field]}}</span>
    </td>
  </tr>
</ng-template>

applyClassCondition(rowData,col_field) {
    if(evaluate condition){
        return 'bg-red';
     }
}

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

What is the most effective method for delivering a Promise after an asynchronous request?

Currently, I am working on creating an asynchronous function in TypeScript that utilizes axios to make an HTTP request and then returns a Promise for the requested data. export async function loadSingleArweaveAbstraction(absId : string) : Promise<Abstra ...

Install a MEAN Stack application on the server of my choosing

My MEAN Stack app is running smoothly in development mode. I am now looking to deploy it on my company's server, but I am struggling to find resources on deploying MEAN apps on a server of my choice. Most of the tutorials I found focus on platforms li ...

Leveraging a sophisticated .d.ts file known as chrome-app.d.ts

Understanding and using .d.ts files can be straightforward for most, like jQuery.d.ts. However, I recently encountered chrome-app.d.ts and found it a bit puzzling on how to import this typings file. In chrome-app.d.ts, there are various module definitions ...

The Angular service is sending back the error message "undefined" when trying to retrieve data with the ID parameter from the requested

When calling a service from a component, I am encountering a 400 bad request error with the following message: "Invalid data 'undefined' for parameter id" It's worth noting that the getProduct method in the API is functioning correctly. ...

Question from a student: What is the best way to transfer information between different classes?

Currently, I am delving into SPFX development. My focus is on constructing a form that incorporates multiple classes in order to gain insight on how they can interact and share data among one another. In this scenario, I have established two distinct clas ...

Dynamic Angular TreeView showcasing nested children branches

I am in need of creating a treeView that can handle dynamic data. Currently, I am utilizing the syncfusion component which can be found at this link. The challenge I am facing is that the data object I receive is incomplete, with the "children" being gene ...

Eliminating an index from a JSON array using Typescript

I'm working with a JSON array/model that is structured as follows: var jsonArray = [0] [1] ... [x] [anotherArray][0] [1] ... [e] My goal is to extract only the arrays from [0] to [x] and save them into their ...

Tips for maintaining a connection in angular

I have a small demo app where I implement a fake login feature that serves its purpose well. However, I am looking to enhance it by persisting the logged-in user status. I have attempted to use the following method: The issue arises when I refresh (F5) th ...

Angular CLI Issue: Project Configuration Not Detected

I've been attempting to execute an Angular program that was developed by a coworker, but I keep encountering the same error message: "The serve command needs to be run in an Angular project, yet a project definition cannot be found." Even after runnin ...

ways to coordinate two subscriptions so that one initiates only when the other one emits

Currently, I am developing an Angular application with a specific scenario. I have an observable signal named dataFetchedEvent$, which indicates that data has been fetched from a remote location. Additionally, there is a form that relies on this remote dat ...

Transform a struggling Observable into a successful one

When working with an HTTP service that returns an observable, I encountered an error during the subscribe process for a specific use case that I would like to address within the successful path. My scenario looks like this: In my service class: class My ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

What is the process of declaring a react-icons icon in TypeScript?

Having a dilemma with declaring the icon in my array that contains name and icon. export const SidebarMenuList: SidebarMenu[] = [ { name: "Discover", icon: <AiOutlineHome />, id: SidebarCategory.Discover, }, ] The SidebarMe ...

Guide to transforming an IdentityMap<String, dynamic> into a UInt8List

I have a cloud function that generates a JavaScript Buffer object, which looks something like this: functions .region("europe-west2") .runWith({ timeoutSeconds: 20, memory: "128MB", }) .https .onCall(asyn ...

How can we effectively implement alert notifications for validating image sizes and formats prior to uploading?

code playground : https://codesandbox.io/s/quizzical-lamport-ql5ep I'm encountering an issue with the code provided in the CodeSandbox link. https://i.sstatic.net/xg3aK.png I've attempted to resolve this issue using various methods, but unfortu ...

Dealing with asynchronous data using mermaid-js in Angular

Currently, I am engrossed in a project that involves retrieving data from the DB asynchronously and utilizing it to create a sequence diagram using mermaid.js' markdown syntax. Nevertheless, an issue has cropped up where the sequence diagram gets rend ...

Enhance the API response for Angular service purposes

I am currently working on modifying the response returned by an API request. At the moment, I receive the response as: [ { name: "Afghanistan" }, { name: "Åland Islands" } ] My goal is to adjust it to: [ { name: "A ...

Unable to import JSX/TSX component from a separate React application into my primary React application

I find myself facing a challenge with integrating two React applications with different setups. Background: I was assigned the task of developing a design system using ReactJS that would be implemented in their primary application. Despite my limited kn ...

What could be the reason for encountering TypeScript within the Vue.js source code?

While exploring the vue.js source code, I stumbled upon some unfamiliar syntax that turned out to be TypeScript after further investigation. What baffled me was finding this TypeScript syntax within a ".js" file, when my understanding is that TypeScript ...

I'm new to NPM and Node.js and I'm currently exploring the differences between global and local dependencies installations, and how they are displayed in the package.json file

I'm primarily a designer who is diving into coding. Recently, I've been assisting with an Angular project at work and needed to learn how to utilize npm to install Angular CLI and its dependencies. Setting up my Angular project was a breeze. I m ...